21xrx.com
2025-03-26 13:56:06 Wednesday
文章检索 我的文章 写文章
C++ Set 的遍历方法
2023-07-04 20:04:29 深夜i     72     0
C++ Set 遍历方法

C++中的Set是一个非常常用的容器,它可以用于存储一组有序的独特元素。但是,如果想要遍历这个Set容器,我们该如何做呢?下面就来介绍一下Set的遍历方法。

在C++中Set容器本身并不提供迭代器,因此我们需要使用C++标准库的迭代器来进行遍历。C++标准库中提供了两种迭代器:正向迭代器和反向迭代器。我们可以使用这两种迭代器来实现Set容器的正向遍历和反向遍历。

1. 正向遍历

对于Set容器的正向遍历,我们可以使用Set容器提供的begin()和end()函数来获取一个指向Set容器起始位置和结束位置的迭代器。我们可以使用STL算法中的for_each()函数或者for循环来进行遍历。

示例代码如下:

#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
int main() {
  set<int> test_set 2;
  
  // 使用for_each()函数进行遍历
  for_each(test_set.begin(), test_set.end(), [](int elem)
    cout << elem << " ";
  );
  // 输出:1 2 3 4 5
  
  cout << endl;
  
  // 使用for循环进行遍历
  for (auto it = test_set.begin(); it != test_set.end(); ++it) {
    cout << *it << " ";
  }
  // 输出:1 2 3 4 5
  
  return 0;
}

上述代码中,我们使用了for_each()函数和for循环两种方式来进行遍历,输出结果都是一样的,分别为1 2 3 4 5。

2. 反向遍历

如果我们需要对Set容器进行反向遍历,即从后往前遍历每个元素。我们可以使用Set容器提供的rbegin()和rend()函数来获取一个指向Set容器最后一个元素和第一个元素的迭代器。我们同样也可以使用STL算法中的for_each()函数或者for循环来进行遍历。

示例代码如下:

#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
int main() {
  set<int> test_set 4;
  
  // 使用for_each()函数进行反向遍历
  for_each(test_set.rbegin(), test_set.rend(), [](int elem)
    cout << elem << " ";
  );
  // 输出:5 4 3 2 1
  
  cout << endl;
  
  // 使用for循环进行反向遍历
  for (auto it = test_set.rbegin(); it != test_set.rend(); ++it) {
    cout << *it << " ";
  }
  // 输出:5 4 3 2 1
  
  return 0;
}

上述代码中,我们依旧使用了for_each()函数和for循环两种方式来进行反向遍历,输出结果也都是一样的,分别为5 4 3 2 1。

总结:

在C++中,Set容器的遍历可以使用begin()、end()、rbegin()和rend()函数来获取迭代器,使用STL算法中的for_each()函数或者for循环进行遍历。无论是正向遍历还是反向遍历,都非常简单易懂。适当的遍历可以让我们更好地应用Set容器,提高代码的效率和可读性。

  
  

评论区