c++ set 遍历
时间: 2024-03-16 08:39:11 浏览: 62
C++中的set是一种有序的容器,它存储唯一的元素,并按照升序进行排序。要遍历set,可以使用迭代器或范围循环。
使用迭代器遍历set的示例代码如下:
```cpp
#include <iostream>
#include <set>
int main() {
std::set<int> mySet = {1, 2, 3, 4, 5};
// 使用迭代器遍历set
std::set<int>::iterator it;
for (it = mySet.begin(); it != mySet.end(); ++it) {
std::cout << *it << " ";
}
return 0;
}
```
使用范围循环遍历set的示例代码如下:
```cpp
#include <iostream>
#include <set>
int main() {
std::set<int> mySet = {1, 2, 3, 4, 5};
// 使用范围循环遍历set
for (const auto& element : mySet) {
std::cout << element << " ";
}
return 0;
}
```
相关问题
c++ unordered_set 遍历
c++中的unordered_set是一种哈希表的实现,它可以用来存储一组不重复的元素。遍历unordered_set可以使用迭代器或者C++11的新语法auto关键字。具体方法如下:
1.使用迭代器:
for(unordered_set<int>::iterator it=s.begin(); it!=s.end(); it++) {
cout<<*it<<" ";
}
2.使用C++11的新语法auto关键字:
for(auto it:s) {
cout<<it<<" ";
}
需要注意的是,unordered_set是无序的,因此遍历的顺序也是无序的。
set反向遍历 C++
在C++中,set是一种有序的容器,它存储唯一的元素,并按照升序进行排序。要进行set的反向遍历,可以使用反向迭代器。
以下是set反向遍历的步骤:
1. 首先,包含set头文件`#include <set>`。
2. 创建一个set对象并插入一些元素。
3. 使用`rbegin()`函数获取set的反向迭代器的起始位置。
4. 使用`rend()`函数获取set的反向迭代器的结束位置。
5. 使用反向迭代器进行遍历,可以使用`--`操作符将迭代器向前移动。
下面是一个示例代码,演示了如何进行set的反向遍历:
```cpp
#include <iostream>
#include <set>
int main() {
std::set<int> mySet = {1, 2, 3, 4, 5};
// 反向遍历
for (auto it = mySet.rbegin(); it != mySet.rend(); ++it) {
std::cout << *it << " ";
}
return 0;
}
```
输出结果为:5 4 3 2 1
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)