c++遍历set的技巧有哪些
在C++中,使用迭代器是遍历std::set
的常用方法。以下是一些遍历std::set
的技巧:
- 使用迭代器循环遍历
std::set
:
std::set<int> mySet = {1, 2, 3, 4, 5};
for (auto it = mySet.begin(); it != mySet.end(); ++it) {
std::cout << *it << " ";
}
- 使用范围循环遍历
std::set
:
std::set<int> mySet = {1, 2, 3, 4, 5};
for (auto value : mySet) {
std::cout << value << " ";
}
- 使用标准算法
std::for_each
遍历std::set
:
std::set<int> mySet = {1, 2, 3, 4, 5};
std::for_each(mySet.begin(), mySet.end(), [](int value) {
std::cout << value << " ";
});
- 使用
std::find
查找指定元素:
std::set<int> mySet = {1, 2, 3, 4, 5};
int target = 3;
auto it = mySet.find(target);
if (it != mySet.end()) {
std::cout << "Element found: " << *it;
} else {
std::cout << "Element not found";
}
这些是一些常用的遍历std::set
的技巧,根据具体情况选择合适的方法来遍历std::set
。