如何反向遍历C ++集?
假设我们有一个集合,那么我们必须反向遍历该集合。因此,如果集合像S=[10,15,26,30,35,40,48,87,98],那么输出将是:988748403530261510。
要以相反的顺序遍历,可以使用reverse_iterator。在这里,我们将使用rbegin()andrend()函数来获取反向迭代器的开始和结束。
示例
#include <iostream>
#include <set>
using namespace std;
int main() {
int arr[] = {10, 15, 26, 30, 35, 40, 48, 87, 98};
set<int> my_set(arr, arr + sizeof(arr) / sizeof(arr[0]));
set<int>::iterator it;
cout << "Elements of Set in forward order: ";
for (it = my_set.begin(); it != my_set.end(); it++)
cout << *it << " ";
set<int>::reverse_iterator rev_it;
cout << "\nElements of Set in reverse order: ";
for (rev_it = my_set.rbegin(); rev_it != my_set.rend(); rev_it++)
cout << *rev_it << " ";
}输出结果
Elements of Set in forward order: 10 15 26 30 35 40 48 87 98 Elements of Set in reverse order: 98 87 48 40 35 30 26 15 10
热门推荐
10 病人祝福语老师寄语简短
11 新娘生孩子祝福语简短
12 婆婆66岁祝福语简短
13 今天孩子高考祝福语简短
14 送彩票生日祝福语简短
15 分别祝福语简短情话英文
16 画室揭牌仪式祝福语简短
17 女友妈妈生日祝福语简短
18 离别赠言离职祝福语简短