如何在 C++ set 中反向遍历?
假设我们有集合 S = [10, 15, 26, 30, 35, 40, 48, 87, 98],反向遍历该集合,输出结果应为:98 87 48 40 35 30 26 15 10。
要反向遍历,我们可以使用 reverse_iterator。这里我们使用 rbegin() 和 rend() 函数获取反向迭代器的开始和结束。
示例
#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
广告