C++ 如何迭代 std::set?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12863256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:41:54  来源:igfitidea点击:

How to iterate std::set?

c++setiteration

提问by Roman

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 ->firstvalue. How I can obtain the value?

没有->first价值。我如何获得价值?

回答by Rob?

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:

如果您有 C++11 功能,则可以使用基于范围的 for 循环

for(auto f : SERVER_IPS) {
  // use f here
}    

回答by Rami Jarrar

Just use the *before it:

只需使用*之前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.

这将取消引用它并允许您访问迭代器当前所在的元素。

回答by vitperov

Another example for the C++11 standard:

C++11 标准的另一个例子:

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

for (const int &number : data)
  cout << number;

回答by Luis B

How do you iterate std::set?

你如何迭代 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;
}