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?
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
}
Another example for the C++11 standard:
set<int> data;
data.insert(4);
data.insert(5);
for (const int &number : data)
cout << number;
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.
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;
}
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++;
}