C ++ map rend()函數(shù)用于以相反的順序將迭代器返回到map的末尾(不是最后一個(gè)元素,而是過(guò)去的最后一個(gè)元素)。這類(lèi)似于非反轉(zhuǎn)容器的第一個(gè)元素之前的元素。
reverse_iterator rend(); // 在 C++ 11 之前 const_reverse_iterator rend() const; // 在 C++ 11 之前 reverse_iterator rend() noexcept; //從 C++ 11 開(kāi)始 const_reverse_iterator rend() const noexcept; //從 C++ 11 開(kāi)始
沒(méi)有
它將反向迭代器返回到反轉(zhuǎn)容器最后一個(gè)元素之后的元素。
讓我們看一下rend()函數(shù)的簡(jiǎn)單示例:
#include <iostream>
#include <map>
using namespace std;
int main ()
{
map<char,int> mymap;
mymap['x'] = 100;
mymap['y'] = 200;
mymap['z'] = 300;
map<char,int>::reverse_iterator rit;
for (rit=mymap.rbegin(); rit!=mymap.rend(); ++rit){
cout << rit->first << " = " << rit->second << '\n';
}
return 0;
}輸出:
z = 300 y = 200 x = 100
在上面的示例中,rend()函數(shù)用于將反向迭代器返回到反向容器的最后一個(gè)元素之后的元素。
因?yàn)閙ap因此按鍵的排序順序存儲(chǔ)元素,所以在map上進(jìn)行迭代將導(dǎo)致上述順序,即鍵的排序順序。
讓我們看一個(gè)簡(jiǎn)單的示例,使用while循環(huán)以相反的順序遍歷map:
#include <iostream>
#include <map>
#include <string>
#include <iterator>
using namespace std;
int main() {
map<string, int> mapEx = {
{ "aaa", 10 },
{ "ddd", 11 },
{ "bbb", 12 },
{ "ccc", 13 }
};
map<string, int>::reverse_iterator it = mapEx.rbegin();
while (it != mapEx.rend()) {
string word = it->first;
int count = it->second;
cout << word << " :: " << count << endl;
it++;
}
return 0;
}輸出:
ddd :: 11 ccc :: 13 bbb :: 12 aaa :: 10
在上面的示例中,我們使用while循環(huán)以相反的順序遍歷map。
因?yàn)閙ap因此按鍵的排序順序存儲(chǔ)元素,所以在map上進(jìn)行迭代將導(dǎo)致上述順序,即鍵的排序順序。
讓我們看一個(gè)簡(jiǎn)單的實(shí)例。
#include <iostream>
#include <map>
using namespace std;
int main(void) {
map<char, int> m = {
{'a', 1},
{'b', 2},
{'c', 3},
{'d', 4},
{'e', 5},
};
cout << "Map以相反的順序包含以下元素:" << endl;
for (auto it = m.rbegin(); it != m.rend(); ++it)
cout << it->first << " = " << it->second << endl;
return 0;
}輸出:
Map以相反的順序包含以下元素: e = 5 d = 4 c = 3 b = 2 a = 1
在上面的示例中,map的元素以相反的順序返回。
讓我們看一個(gè)簡(jiǎn)單的示例,對(duì)最高分進(jìn)行排序和計(jì)算。
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main ()
{
map<int,int> emp = {
{ 1000, 10},
{ 2500, 20 },
{ 4500, 30 },
{ 3000, 40 },
{ 5500, 50 }};
cout << "Salary" << " | " << "ID" << '\n';
cout<<"______________________\n";
map<int,int>::reverse_iterator rit;
for (rit=emp.rbegin(); rit!=emp.rend(); ++rit){}{
cout << rit->first << " | " << rit->second << '\n';
auto ite = emp.rbegin();
cout << "\nHighest salary: "<< ite->first <<" \n";
cout << "ID is: "<< ite->second << "\n";
}
return 0;
}輸出:
Salary | ID ______________________ 5500 | 50 4500 | 30 3000 | 40 2500 | 20 1000 | 10 Highest salary: 5500 ID is: 50
在上面的示例中,實(shí)現(xiàn)了一個(gè)容器emp,其中將ID存儲(chǔ)為值,并將薪水存儲(chǔ)為鍵。這使我們能夠利用map中的自動(dòng)排序功能,并使我們能夠確定薪水最高的元素的ID。