C ++ map rbegin()函数用于返回指向map容器最后一个元素的反向迭代器。
map的反向迭代器沿反向移动并递增,直到到达map容器的开头(第一个元素)。
reverse_iterator rbegin(); // 在 C++ 11 之前 const_reverse_iterator rbegin() const; // 在 C++ 11 之前 reverse_iterator rbegin() noexcept; //从 C++ 11 开始 const_reverse_iterator rbegin() const noexcept; //从 C++ 11 开始
没有
它返回指向map的最后一个元素的反向迭代器。
让我们看一个简单的rbegin()函数示例。
#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
在上面的示例中,rbegin()函数用于返回指向mymap容器中最后一个元素的反向迭代器。
因为map因此按键的排序顺序存储元素,所以在map上进行迭代将导致上述顺序,即键的排序顺序。
让我们看一个简单的示例,使用while循环以相反的顺序遍历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循环以相反的顺序遍历map,并且rbegin()函数初始化map的最后一个元素。
因为map因此按键的排序顺序存储元素,所以在map上进行迭代将导致上述顺序,即键的排序顺序。
让我们看一个简单的示例,以获取反向map的第一个元素。
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main ()
{
map<int,int> m1 = {
{ 1, 10},
{ 2, 20 },
{ 3, 30 } };
auto ite = m1.rbegin();
cout << "反向map容器m1的第一个元素是: ";
cout << "{" << ite->first << ", "
<< ite->second << "}\n";
return 0;
}输出:
反向map容器m1的第一个元素是: {3, 30}在上面的示例中,rbegin()函数返回反转容器m1的第一个元素,即{3,30}。
让我们看一个简单的示例,对最高分进行排序和计算。
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main ()
{
map<int,int> marks = {
{ 400, 10},
{ 312, 20 },
{ 480, 30 },
{ 300, 40 },
{ 425, 50 }};
cout << "Marks" << " | " << "Roll Number" << '\n';
cout<<"______________________\n";
map<int,int>::reverse_iterator rit;
for (rit=marks.rbegin(); rit!=marks.rend(); ++rit)
cout << rit->first << " | " << rit->second << '\n';
auto ite = marks.rbegin();
cout << "\n最高分是: "<< ite->first <<" \n";
cout << "Topper的卷数是: "<< ite->second << "\n";
return 0;
}输出:
Marks | Roll Number ______________________ 480 | 30 425 | 50 400 | 10 312 | 20 300 | 40 最高分是: 480 Topper的卷数是: 30
在上面的示例中,实现了map标记,其中将“卷号”存储为值,并将标记存储为键。这使我们能够利用map中的自动排序功能,并使我们能够识别标记最高的元素的卷号。