简体   繁体   English

如何在C ++中迭代无序集?

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

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. 无济于事。

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 auto support, 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! 希望这可以帮助!

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 begin and end functions (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) { 
    ...
}

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM