C ++ map crend()函数用于将常量迭代器以相反的顺序返回到map的末尾(返回一个常量反向迭代器,指向第一个元素之前虚拟的元素)。这类似于非反转容器的第一个元素之前的元素。
注意:-这是一个占位符。此位置没有元素,尝试访问是未定义的行为。
注意:常量迭代器是指向常量内容的迭代器。
const_reverse_iterator crend() const noexcept; //从 C++ 11 开始
没有
它将const_reverse_iterator返回到反转容器的最后一个元素之后的元素。
让我们看一个简单的crend()函数示例。
#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>::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()函数将常量反向迭代器返回到反向容器最后一个元素之后的元素。
因为map因此按键的排序顺序存储元素,所以在map上进行迭代将导致上述顺序,即键的排序顺序。
让我们看一个简单的示例,使用while循环以相反的顺序遍历map。
#include <iostream>
#include <map>
#include <string>
#include <iterator>
using namespace std;
int main() {
//创建和初始化String和Ints的map
map<string, int> mapEx = {
{ "aaa", 10 },
{ "ddd", 11 },
{ "bbb", 12 },
{ "ccc", 13 }
};
//创建一个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循环以相反的顺序对map进行const_iterate。
因为map因此按键的排序顺序存储元素,所以在map上进行迭代将导致上述顺序,即键的排序顺序。
让我们看一个简单的实例。
#include <iostream>
#include <map>
using namespace std;
int main(void) {
/* Initializer_list构造函数 */
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
在上面的示例中,实现了一个map容器emp,其中将ID存储为值,并将薪水存储为键。这使我们能够利用map中的自动排序功能,并使我们能够确定薪水最高的元素的ID。