How to iterate std::set?

Roman picture Roman · Oct 12, 2012 · Viewed 209.7k times · Source

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?

Answer

Robᵩ picture Robᵩ · Oct 12, 2012

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
}