C ++ set rend()函數(shù)用于以相反的順序將迭代器返回到集合的末尾(不是最后一個元素,而是過去的最后一個元素)。這類似于非反轉(zhuǎn)容器的第一個元素之前的元素。
reverse_iterator rend(); //直到 C ++ 11 const_reverse_iterator rend() const; //直到 C ++ 11 reverse_iterator rend() noexcept; //從 C++ 11開始 const_reverse_iterator rend() const noexcept; //從 C++ 11開始
沒有
它將反向迭代器返回到反轉(zhuǎn)容器最后一個元素之后的元素。
不變。
沒有變化。
容器被訪問。const版本和非const版本都不會修改容器。
同時訪問集合的元素是安全的。
此函數(shù)永遠(yuǎn)不會引發(fā)異常。
讓我們看一下rend()函數(shù)的簡單示例:
#include <iostream> #include <set> using namespace std; int main () { set<int> myset = {40,50,20,10,30}; cout << "元素是 :"; for (auto rit = myset.rbegin(); rit != myset.rend(); ++rit) cout << ' ' << *rit; cout << '\n'; return 0; }
輸出:
元素是 : 50 40 30 20 10
在上面的示例中,rend()函數(shù)用于將反向迭代器返回到反向容器的最后一個元素之后的元素。
因為set因此按鍵的排序順序存儲元素,所以對set進(jìn)行迭代將導(dǎo)致上述順序,即鍵的排序順序。
讓我們看一個簡單的示例,使用while循環(huán)以相反的順序遍歷集合:
#include <iostream> #include <set> #include <string> #include <iterator> using namespace std; int main() { // 創(chuàng)建和初始化一組字符串& int set<string> setEx = {"aaa", "bbb", "ccc", "ddd"}; // 創(chuàng)建一個set迭代器并指向set的末尾 set<string>::reverse_iterator it = setEx.rbegin(); // 使用迭代器遍歷集合直到開始。 while (it != setEx.rend()) { // 從它所指向的元素訪問鍵。 string word = *it; cout << word << endl; // 增加迭代器以指向下一個條目 it++; } return 0; }
輸出:
ddd ccc bbb aaa
在上面的示例中,我們使用while循環(huán)以相反的順序遍歷集合。
因為set因此按鍵的排序順序存儲元素,所以對set進(jìn)行迭代將導(dǎo)致上述順序,即鍵的排序順序。
讓我們看一個簡單的實例:
#include <set> #include <iostream> int main() { using namespace std; set <int> s1; set <int>::iterator s1_Iter; set <int>::reverse_iterator s1_rIter; s1.insert( 10 ); s1.insert( 20 ); s1.insert( 30 ); s1_rIter = s1.rend( ); s1_rIter--; cout << "反集的最后一個元素是 " << *s1_rIter << "." << endl; // end可用于終止迭代 // 按順序通過一個集合 cout << "set集合是: "; for ( s1_Iter = s1.begin( ) ; s1_Iter != s1.end( ); s1_Iter++ ) cout << *s1_Iter << " "; cout << "." << endl; // rend可用于終止迭代 // 以相反的順序通過一個集合 cout << "反向集為: "; for ( s1_rIter = s1.rbegin( ) ; s1_rIter != s1.rend( ); s1_rIter++ ) cout << *s1_rIter << " "; cout << "." << endl; s1_rIter = s1.rend( ); s1_rIter--; s1.erase ( *s1_rIter ); s1_rIter = s1.rend( ); --s1_rIter; cout << "刪除后, 最后一個元素 " << "反向集為 " << *s1_rIter << "." << endl; }
輸出:
反集的最后一個元素是 10. set集合是: 10 20 30 . 反向集為: 30 20 10 . 刪除后, 反集的最后一個元素是 20.
在上面的示例中,set的元素以相反的順序返回。
讓我們看一個簡單的示例來對最高分進(jìn)行排序和計算:
#include <iostream> #include <string> #include <set> using namespace std; int main () { set<int> emp = {1000,2500,4500,5000,3000}; cout << "薪水" << '\n'; cout<<"______________________\n"; set<int>::reverse_iterator rit; for (rit=emp.rbegin(); rit!=emp.rend(); ++rit) cout << *rit<< '\n'; auto ite = emp.rbegin(); cout << "\n最高薪水: "<< *ite <<" \n"; return 0; }
輸出:
薪水 ______________________ 5000 4500 3000 2500 1000 最高薪水: 5000
在上面的示例中,實現(xiàn)了一個set emp,其中將ID存儲為值,而薪水存儲為鍵。這使我們能夠利用集合中的自動排序功能,并使我們能夠識別薪水最高的元素的ID。