如何遍历 C++ 中的无序集合?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9087217/
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 12:16:47  来源:igfitidea点击:

How does one iterate through an unordered set in C++?

c++c++11iterationunordered-set

提问by dangerChihuahua007

Suppose I have an unordered set

假设我有一个无序集合

unordered_set<int> my_set;
myset.insert(1);
myset.insert(2);
myset.insert(3);

How do I iterate through it? I don't need to iterate in any order - just as long as I reach each element once. I tried

我如何遍历它?我不需要以任何顺序迭代——只要我到达每个元素一次。我试过

for (int i = 0; i < my_set.size(); i++)
     cout << my_set[i];

to no avail.

无济于事。

回答by templatetypedef

You can use the new range-based for loop:

您可以使用新的基于范围的 for 循环:

std::unordered_set<T> mySet;
for (const auto& elem: mySet) {
    /* ... process elem ... */
}

Or, you can use the more traditional iterator-based loop:

或者,您可以使用更传统的基于迭代器的循环:

std::unordered_set<T> mySet;
for (auto itr = mySet.begin(); itr != mySet.end(); ++itr) {
    /* ... process *itr ... */
}

Or, if you don't have autosupport, perhaps because you don't have C++11 support on your compiler:

或者,如果您没有auto支持,可能是因为您的编译器没有 C++11 支持:

std::unordered_set<T> mySet;
for (std::unordered_set<T>::iterator itr = mySet.begin(); itr != mySet.end(); ++itr) {
    /* ... process *itr ... */
}

Hope this helps!

希望这可以帮助!

回答by Kos

Just like any other collection:

就像任何其他集合一样:

for (auto i = my_set.begin(); i != my_set.end(); ++i) {
    std::cout << (*i) << std::endl;
}

Or a bit more generic way using overloads of beginand endfunctions (you can write overloads for your own types; they also work on plain arrays):

或者使用beginend函数重载的更通用的方法(您可以为自己的类型编写重载;它们也适用于普通数组):

for (auto i = begin(my_set); i != end(my_set); ++i) { 
    ...
}

回答by Mario

Never used them so far, but I'd guess you can use an iterator the same way you do with std::set:

到目前为止从未使用过它们,但我猜你可以像使用 迭代器一样使用迭代器std::set

for(unordered_set<int>::iterator a = my_set.begin(); a != my_set.end(); ++a) {
    int some_int = *a;
}