21xrx.com
2024-09-19 11:28:46 Thursday
登录
文章检索 我的文章 写文章
C++ Set 的遍历方法
2023-07-14 12:10:44 深夜i     --     --
C++ Set 遍历方法

C++ Set是一种STL容器,用于以特定的排序顺序存储独特的元素集。Set中的每个元素都是唯一的,没有相同的元素存在。C++ Set是用红黑树实现的,因此插入、查找和删除都非常快。在使用C++ Set时,有时候需要遍历容器中的元素,下面将介绍几种方法来遍历C++ Set。

1.使用迭代器遍历Set

C++ Set提供了一对迭代器begin()和end(),通过这对迭代器,可以依次遍历整个Set容器中的元素。需要注意的是,C++ Set是有序的,因此迭代器返回的元素也是按照一定的排序顺序返回的。

以下是使用迭代器遍历Set的示例代码:


#include <iostream>

#include <set>

using namespace std;

int main()

{

  set<int> setExample = 5 ;

  set<int>::iterator it;

  for (it = setExample.begin(); it != setExample.end(); it++)

  {

    cout << *it << " ";

  }

  return 0;

}

运行上面的代码,将输出以下结果:


1 2 3 4 5

2.使用auto关键字遍历Set

C++11引入了auto关键字,可以使编译器根据赋值操作的结果自动推断变量的类型。利用auto关键字,可以简化Set的遍历操作,如下所示:


#include <iostream>

#include <set>

using namespace std;

int main()

{

  set<int> setExample = 4;

  for (auto it = setExample.begin(); it != setExample.end(); it++)

  {

    cout << *it << " ";

  }

  return 0;

}

其中,auto关键字自动推断出变量it的类型为set ::iterator类型。

3.使用范围for循环遍历Set

在C++11中,引入了新的范围for循环,它还可以用于直接遍历整个Set容器。需要注意的是,范围for循环中直接遍历的是Set容器的元素,而非迭代器。以下是使用范围for循环遍历Set的示例代码:


#include <iostream>

#include <set>

using namespace std;

int main()

{

  set<int> setExample = 1;

  for (int value : setExample)

  

    cout << value << " ";

  

  return 0;

}

运行上面的代码,将输出以下结果:


1 2 3 4 5

C++ Set是一种非常有用的STL容器,可以用来存储独特的元素集,还提供了多种遍历方式,方便用户直接获取容器中的所有元素。希望本文介绍的C++ Set遍历方法能够帮助大家更好地学习和使用C++ Set。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复