119

I have this code:

std::set<unsigned long>::iterator it;
for (it = SERVER_IPS.begin(); it != SERVER_IPS.end(); ++it) {
    u_long f = it; // error here
}

There is no ->first value. How I can obtain the value?

mtk
  • 13,221
  • 16
  • 72
  • 112
Roman
  • 1,377
  • 2
  • 11
  • 12

5 Answers5

192

You must dereference the iterator in order to retrieve the member of your set.

std::set<unsigned long>::iterator it;
for (it = SERVER_IPS.begin(); it != SERVER_IPS.end(); ++it) {
    u_long f = *it; // Note the "*" here
}

If you have C++11 features, you can use a range-based for loop:

for(auto f : SERVER_IPS) {
  // use f here
}    
mtk
  • 13,221
  • 16
  • 72
  • 112
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
21

Another example for the C++11 standard:

set<int> data;
data.insert(4);
data.insert(5);

for (const int &number : data)
  cout << number;
Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
vitperov
  • 1,347
  • 17
  • 20
18

Just use the * before it:

set<unsigned long>::iterator it;
for (it = myset.begin(); it != myset.end(); ++it) {
    cout << *it;
}

This dereferences it and allows you to access the element the iterator is currently on.

Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49
Rami Jarrar
  • 4,523
  • 7
  • 36
  • 52
  • 10
    Just a minor note: it is generally preferred to use ++it instead of it++ in for loops to avoid one extra copy of the iterator. – user2891462 May 28 '15 at 12:04
7

How do you iterate std::set?

int main(int argc,char *argv[]) 
{
    std::set<int> mset;
    mset.insert(1); 
    mset.insert(2);
    mset.insert(3);

    for ( auto it = mset.begin(); it != mset.end(); it++ )
        std::cout << *it;
}
mtk
  • 13,221
  • 16
  • 72
  • 112
Luis B
  • 1,684
  • 3
  • 15
  • 25
2

One more thing that might be useful for beginners is since std::set is not allocated with contiguous memory chunks if someone want to iterate till kth element normal way will not work.

Example:

std::vector<int> vec{1, 2, 3, 4, 5};
int k = 3;
for (auto itr = vec.begin(); itr < vec.begin() + k; itr++)
    cout << *itr << " ";
std::unordered_set<int> s{1, 2, 3, 4, 5};
int k = 3;
int index = 0;
auto itr = s.begin();
while (true)
{
    if (index == k)
        break;
    cout << *itr++ << " ";
    index++;
}
Bean
  • 67
  • 7