C++ set crend()函数用于以反向顺序将常量迭代器返回到集合的末尾(不是最后一个元素,而是过去的最后一个元素) 。这类似于非反转集合的第一个元素之前的元素。
const_reverse_iterator crend() const noexcept; //since C++ 11
它将const_reverse_iterator返回到反转集合的最后一个元素之后的元素。
让我们看一下crend()函数的简单示例:
#include <iostream> #include <set> using namespace std; int main () { set<int> myset = {40,20,50,10,30}; cout << "myset in reverse order:"; for (auto rit=myset.crbegin(); rit != myset.crend(); ++rit) cout << ' ' << *rit; cout << '\n'; return 0; }
输出:
myset in reverse order: 50 40 30 20 10
在上面的示例中,crend()函数用于将常量反向迭代器返回到反向集合最后一个元素之后的元素。
因为集合因此按键的排序顺序存储元素,所以对集合进行迭代将导致上述顺序,即键的排序顺序。
让我们看一个简单的示例,使用while循环以相反的顺序遍历集合:
#include <iostream> #include <set> #include <string> #include <iterator> using namespace std; int main() { // Creating & Initializing a set of String & Ints set<string> setEx = {"ccc", "ddd", "aaa", "bbb"}; // Create a set iterator and point to the end of set set<string>::const_reverse_iterator it = setEx.crbegin(); // Iterate over the set using Iterator till beginning. while (it != setEx.crend()) { // Accessing KEY from element pointed by it. string word = *it; cout << word << endl; // Increment the Iterator to point to next entry it++; } return 0; }
输出:
ddd ccc bbb aaa
在上面的示例中,我们使用while循环以相反的顺序对集合进行const_iterate。
链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-set-crend-function.html
来源:LearnFk无涯教程网
因为集合因此按键的排序顺序存储元素,所以对集合进行迭代将导致上述顺序,即键的排序顺序。
让我们看一个简单的例子:
#include <iostream> #include <set> #include <algorithm> using namespace std; int main() { set<int> c = {3, 1, 2}; for_each(c.crbegin(), c.crend(), [](const int& x) { cout << x << endl; }); }
输出:
3 2 1
在上面的示例中,set的元素以相反的顺序返回。
让我们看一个简单的示例来对最高分进行排序和计算:
#include <iostream> #include <string> #include <set> using namespace std; int main () { set<int> emp = {1000,2500,4500,1200,3000}; cout << "Salary"<< '\n'; cout<<"______________________\n"; set<int>::const_reverse_iterator rit; for (rit=emp.crbegin(); rit!=emp.crend(); ++rit) cout << *rit<< '\n'; auto ite = emp.crbegin(); cout << "\nHighest salary: "<< *ite <<" \n"; return 0; }
输出:
Salary ______________________ 4500 3000 2500 1200 1000 Highest salary: 4500
在上面的示例中,实现了一个set emp,其中薪水存储为键。这使我们能够利用工资的自动排序函数,并确定最高工资。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)