C ++ set crend()函數(shù)用于以相反的順序將常量迭代器返回到集合的末尾(最后一個(gè)元素之后的元素)。這類似于非反轉(zhuǎn)容器的第一個(gè)元素之前的元素。
const_reverse_iterator crend() const noexcept; //從 C++ 11開(kāi)始
沒(méi)有
它將const_reverse_iterator返回到反轉(zhuǎn)容器的最后一個(gè)元素之后的元素。
不變。
沒(méi)有變化。
容器被訪問(wèn)。
同時(shí)訪問(wèn)集合的元素是安全的。
此函數(shù)永遠(yuǎn)不會(huì)引發(fā)異常。
讓我們看一下crend()函數(shù)的簡(jiǎn)單示例:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
set<int> myset = {40,20,50,10,30};
cout << "myset以相反的順序:";
for (auto rit=myset.crbegin(); rit != myset.crend(); ++rit)
cout << ' ' << *rit;
cout << '\n';
return 0;
}輸出:
myset以相反的順序: 50 40 30 20 10
在上面的示例中,使用crend()函數(shù)將常量反向迭代器返回到反向容器最后一個(gè)元素之后的元素。
因?yàn)閟et因此按鍵的排序順序存儲(chǔ)元素,所以對(duì)set進(jìn)行迭代將導(dǎo)致上述順序,即鍵的排序順序。
讓我們看一個(gè)簡(jiǎn)單的示例,使用while循環(huán)以相反的順序遍歷集合:
#include <iostream>
#include <set>
#include <string>
#include <iterator>
using namespace std;
int main() {
// 創(chuàng)建和初始化一組字符串& int
set<string> setEx = {"ccc", "ddd", "aaa", "bbb"};
//創(chuàng)建一個(gè)set迭代器并指向set的末尾
set<string>::const_reverse_iterator it = setEx.crbegin();
// 使用迭代器遍歷集合直到開(kāi)始。
while (it != setEx.crend()) {
// 從它所指向的元素訪問(wèn)鍵。
string word = *it;
cout << word << endl;
// 遞增迭代器以指向下一個(gè)條目
it++;
}
return 0;
}輸出:
ddd ccc bbb aaa
在上面的示例中,我們使用while循環(huán)以相反的順序?qū)线M(jìn)行const_iterate。
因?yàn)閟et因此按鍵的排序順序存儲(chǔ)元素,所以對(duì)set進(jìn)行迭代將導(dǎo)致上述順序,即鍵的排序順序。
讓我們看一個(gè)簡(jiǎn)單的實(shí)例:
#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的元素以相反的順序返回。
讓我們看一個(gè)簡(jiǎn)單的示例來(lái)對(duì)最高分進(jìn)行排序和計(jì)算:
#include <iostream>
#include <string>
#include <set>
using namespace std;
int main ()
{
set<int> emp = {1000,2500,4500,1200,3000};
cout << "薪水"<< '\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 << "\n最高薪水: "<< *ite <<" \n";
return 0;
}輸出:
薪水 ______________________ 4500 3000 2500 1200 1000 最高薪水: 4500
在上面的示例中,實(shí)現(xiàn)了一個(gè)set 集合emp,其中薪水存儲(chǔ)為鍵。這使我們能夠利用工資的自動(dòng)排序功能,并確定最高工資。