C ++ map crend()函數(shù)用于將常量迭代器以相反的順序返回到map的末尾(返回一個常量反向迭代器,指向第一個元素之前虛擬的元素)。這類似于非反轉(zhuǎn)容器的第一個元素之前的元素。
注意:-這是一個占位符。此位置沒有元素,嘗試訪問是未定義的行為。
注意:常量迭代器是指向常量內(nèi)容的迭代器。
const_reverse_iterator crend() const noexcept; //從 C++ 11 開始
沒有
它將const_reverse_iterator返回到反轉(zhuǎn)容器的最后一個元素之后的元素。
讓我們看一個簡單的crend()函數(shù)示例。
#include <iostream>
#include <map>
using namespace std;
int main ()
{
map<char,int> mymap;
mymap['x'] = 100;
mymap['y'] = 200;
mymap['z'] = 300;
// 展示內(nèi)容:
map<char,int>::const_reverse_iterator rit;
for (rit=mymap.crbegin(); rit!=mymap.crend(); ++rit)
cout << rit->first << " = " << rit->second << '\n';
return 0;
}輸出:
z = 300 y = 200 x = 100
在上面的示例中,使用crend()函數(shù)將常量反向迭代器返回到反向容器最后一個元素之后的元素。
因為map因此按鍵的排序順序存儲元素,所以在map上進行迭代將導(dǎo)致上述順序,即鍵的排序順序。
讓我們看一個簡單的示例,使用while循環(huán)以相反的順序遍歷map。
#include <iostream>
#include <map>
#include <string>
#include <iterator>
using namespace std;
int main() {
//創(chuàng)建和初始化String和Ints的map
map<string, int> mapEx = {
{ "aaa", 10 },
{ "ddd", 11 },
{ "bbb", 12 },
{ "ccc", 13 }
};
//創(chuàng)建一個map迭代器并指向map的末尾
map<string, int>::const_reverse_iterator it = mapEx.crbegin();
//使用Iterator迭代map直到開始。
while (it != mapEx.crend()) {
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)以相反的順序?qū)ap進行const_iterate。
因為map因此按鍵的排序順序存儲元素,所以在map上進行迭代將導(dǎo)致上述順序,即鍵的排序順序。
讓我們看一個簡單的實例。
#include <iostream>
#include <map>
using namespace std;
int main(void) {
/* Initializer_list構(gòu)造函數(shù) */
map<char, int> m = {
{'a', 1},
{'b', 2},
{'c', 3},
{'d', 4},
{'e', 5},
};
cout << "Map以相反的順序包含以下元素:" << endl;
for (auto it = m.crbegin(); it != m.crend(); ++it)
cout << it->first << " = " << it->second << endl;
return 0;
}輸出:
Map以相反的順序包含以下元素: e = 5 d = 4 c = 3 b = 2 a = 1
在上面的示例中,map的元素以相反的順序返回。
讓我們看一個簡單的示例,對最高分進行排序和計算。
#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 << "薪水 " << " | " << "ID" << '\n';
cout<<"______________________\n";
map<int,int>::const_reverse_iterator rit;
for (rit=emp.crbegin(); rit!=emp.crend(); ++rit)
cout << rit->first << " | " << rit->second << '\n';
auto ite = emp.crbegin();
cout << "\n最高薪水: "<< ite->first <<" \n";
cout << "ID is: "<< ite->second << "\n";
return 0;
}輸出:
薪水 | ID ______________________ 5500 | 50 4500 | 30 3000 | 40 2500 | 20 1000 | 10 最高薪水: 5500 ID is: 50
在上面的示例中,實現(xiàn)了一個map容器emp,其中將ID存儲為值,并將薪水存儲為鍵。這使我們能夠利用map中的自動排序功能,并使我們能夠確定薪水最高的元素的ID。