How to iterate std::set?

前端 未结 4 1718
南方客
南方客 2020-11-30 01:37

I have this code:

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


        
相关标签:
4条回答
  • 2020-11-30 01:55

    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.

    0 讨论(0)
  • 2020-11-30 02:02

    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
    }    
    
    0 讨论(0)
  • 2020-11-30 02:12

    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;
    }
    
    0 讨论(0)
  • 2020-11-30 02:18

    Another example for the C++11 standard:

    set<int> data;
    data.insert(4);
    data.insert(5);
    
    for (const int &number : data)
      cout << number;
    
    0 讨论(0)
提交回复
热议问题