Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate std::set?

Tags:

c++

iteration

set

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?

like image 757
Roman Avatar asked Oct 12 '12 16:10

Roman


People also ask

Can I iterate through a set?

There is no way to iterate over a set without an iterator, apart from accessing the underlying structure that holds the data through reflection, and replicating the code provided by Set#iterator...

Can you iterate through a set C++?

Iterate over a set using an iterator. Iterate over a set in backward direction using reverse_iterator. Iterate over a set using range-based for loop. Iterate over a set using for_each loop.

How do you iterate into a set?

Example 2: Iterate through Set using iterator() We have used the iterator() method to iterate over the set. Here, hasNext() - returns true if there is next element in the set. next() - returns the next element of the set.

Can you iterate through a set with a for loop?

Iterating over Set using IteratorYou can use while or for loop along with hasNext(), which returns true if there are more elements in the Set.


2 Answers

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 }     
like image 92
Robᵩ Avatar answered Sep 28 '22 06:09

Robᵩ


Another example for the C++11 standard:

set<int> data; data.insert(4); data.insert(5);  for (const int &number : data)   cout << number; 
like image 34
vitperov Avatar answered Sep 28 '22 05:09

vitperov