如何在C++中反向遍历一个Set

如何在C++中反向遍历一个Set

给定一个Set,任务是以反向顺序遍历这个Set。

示例:

输入: set=[10 20 30 70 80 90 100 40 50 60]
输出: 100 90 80 70 60 50 40 30 20 10
输入: set=[1 2 3 4 5]
输出: 5 4 3 2 1

方法: 要反向遍历Set,可以在其上声明一个反向迭代器,并借助rbegin()和rend()函数从最后一个元素到第一个元素遍历Set。

  1. 获取Set
  2. 在该Set上声明反向迭代器。
  3. 通过rbegin()和rend()函数从最后一个元素到第一个元素遍历Set。

以下是上述方法的实现代码:

程序:

#include <bits/stdc++.h>
using namespace std;
 
int main()
{
 
    // Get the set
    int arr[] = { 14, 12, 15, 11, 10 };
 
    // initializes the set from an array
    set<int> s(arr, arr + sizeof(arr) / sizeof(arr[0]));
 
    // declare iterator on set
    set<int>::iterator it;
 
    cout << "Elements of Set in normal order:\n";
 
    // prints all elements in normal order
    // using begin() and end() methods
    for (it = s.begin(); it != s.end(); it++)
        cout << *it << " ";
 
    // declare reverse_iterator on set
    set<int>::reverse_iterator rit;
 
    cout << "\nElements of Set in reverse order:\n";
 
    // prints all elements in reverse order
    // using rbegin() and rend() methods
    for (rit = s.rbegin(); rit != s.rend(); rit++)
        cout << *rit << " ";
 
    return 0;
}  

输出:

Elements of Set in normal order:
10 11 12 14 15 
Elements of Set in reverse order:
15 14 12 11 10

时间复杂度: O(n),其中n是给定Set中的元素个数。

辅助空间复杂度: O(n)。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程