c++

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

小樊
84
2024-06-24 16:25:29
栏目: 编程语言

在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

0
看了该问题的人还看了