C ++ set crbegin()函數(shù)用于返回一個常量反向迭代器,該迭代器引用set容器中的最后一個元素。
set的常量反向迭代器沿反向移動并遞增,直到到達set容器的開頭(第一個元素)并指向常量元素。
const_reverse_iterator crbegin() const noexcept; //since C++ 11
沒有
它返回一個常量反向迭代器,該迭代器指向集合的最后一個元素。
沒有
它返回一個常數(shù)反向迭代器,該迭代器指向多圖的最后一個元素。
不變。
沒有變化。
容器被訪問。
同時訪問集合的元素是安全的。
此函數(shù)從不拋出異常。
讓我們看一下crbegin()函數(shù)的簡單示例:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
set<int> myset = {50,20,40,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
在上面的示例中,使用crbegin()函數(shù)返回一個常量反向迭代器,該迭代器指向myset集中的最后一個元素。
因為set因此按鍵的排序順序存儲元素,所以對set進行迭代將導(dǎo)致上述順序,即鍵的排序順序。
讓我們看一個簡單的示例,使用while循環(huán)以相反的順序遍歷集合:
#include <iostream>
#include <set>
#include <string>
#include <iterator>
using namespace std;
int main() {
// 創(chuàng)建和初始化一組字符串 & int
set<string> setEx = {"bbb", "ccc", "aaa", "ddd"};
//創(chuàng)建一個set迭代器并指向set的末尾
set<string>::const_reverse_iterator it = setEx.crbegin();
// 使用迭代器遍歷集合直到開始。
while (it != setEx.crend()) {
//從它所指向的元素訪問鍵。
string word = *it;
cout << word << endl;
// 增加迭代器以指向下一個條目
it++;
}
return 0;
}輸出:
ddd ccc bbb aaa
在上面的示例中,我們使用while循環(huán)以相反的順序?qū)线M行const_iterate,并使用crbegin()函數(shù)初始化集合的最后一個元素。
因為set因此按鍵的排序順序存儲元素,所以對set進行迭代將導(dǎo)致上述順序,即鍵的排序順序。
讓我們看一個簡單的示例,以獲取反向集合的第一個元素:
#include <iostream>
#include <string>
#include <set>
using namespace std;
int main ()
{
set<int> s1 = {20,40,10,30};
auto ite = s1.crbegin();
cout << "反向集s1的第一個元素是: ";
cout << *ite;
return 0;
}輸出:
反向集s1的第一個元素是: 40
在上面的示例中,crbegin()函數(shù)返回反向集s1的第一個元素,即40。
讓我們看一個簡單的示例來對最高分進行排序和計算:
#include <iostream>
#include <string>
#include <set>
using namespace std;
int main ()
{
set<int> marks = {400, 220, 300, 250, 365};
cout << "Marks" << " | " << "Roll Number" << '\n';
cout<<"______________________\n";
set<int>::const_reverse_iterator rit;
for (rit=marks.crbegin(); rit!=marks.crend(); ++rit)
cout << *rit<< '\n';
auto ite = marks.crbegin();
cout << "\n最高分?jǐn)?shù)是: "<< *ite<<" \n";
return 0;
}輸出:
Marks | Roll Number ______________________ 400 365 300 250 220 最高分?jǐn)?shù)是: 400
在上面的示例中,實現(xiàn)了一個集合標(biāo)記,其中該集合的元素存儲為鍵。函數(shù)crbegin()使我們能夠利用集合中的自動排序功能,并識別最高分?jǐn)?shù)。