c++

c++遍历set的技巧有哪些

小樊
200
2024-06-24 16:25:29
栏目: 编程语言
C++开发者专用服务器,限时0元免费领! 查看>>

在C++中,使用迭代器是遍历std::set的常用方法。以下是一些遍历std::set的技巧:

  1. 使用迭代器循环遍历std::set
std::set<int> mySet = {1, 2, 3, 4, 5};

for (auto it = mySet.begin(); it != mySet.end(); ++it) {
    std::cout << *it << " ";
}
  1. 使用范围循环遍历std::set
std::set<int> mySet = {1, 2, 3, 4, 5};

for (auto value : mySet) {
    std::cout << value << " ";
}
  1. 使用标准算法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 << " ";
});
  1. 使用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

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

相关推荐:C++ std::set的递归遍历技巧

0
看了该问题的人还看了