如何反向遍历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