English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C ++ map crbegin()函數用於返回參考map容器中最後一個元素的常數反向迭代器。
常量map的反向迭代器將反向移動並遞增,直到到達map容器的開頭(第一個元素)並指向常量元素。
const_reverse_iterator crbegin() const noexcept; //從 C++ 11 開始
沒有
它返回一個常數反向迭代器,指向map的最後一個元素。
讓我們看一個簡單的crbegin()函數示例。
#include <iostream> #include <map> using namespace std; int main () { map<char,int> mymap; mymap['b'] = 100; mymap['a'] = 200; mymap['c'] = 300; cout << "以相反的順序排列mymap:"; for (auto rit = mymap.crbegin(); rit != mymap.crend(); ++rit) cout << " [" << rit->first << ':' << rit->second << ']'; cout << '\n'; return 0; }
출력:
以相反的順序排列mymap: [c:300] [b:100] [a:200]
在上面的示例中,使用crbegin()函數返回一個常數反向迭代器,該迭代器指向mymap容器中的最後一個元素。
因為map按鍵的排序順序存儲元素。因此,在map上進行迭代將導致上述順序,即鍵的排序順序。
讓我們看一個簡單的示例,使用while循環以相反的順序遍歷map。
#include <iostream> #include <map> #include <string> #include <iterator> using namespace std; int main() { // 创建和初始化string和int的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()) { //從其指向的元素訪問KEY。 string word = it->first; //從它所指向的元素中訪問VALUE。 int count = it->second; }}} //cout << word << " :: " << count << endl; 이터레이터를 증가시켜 다음 항목을 가리키도록 합니다++it } return 0; }
출력:
; 11 ddd :: 13 ccc :: 12 bbb :: 10
aaa ::
위의 예제에서는 while 루프를 사용하여 map를 반대로 순회하며 const_iterate를 사용하고 crbegin() 함수를 통해 map의 마지막 요소를 초기화했습니다.
map에 있을 때, 키의 정렬 순서에 따라 요소가 저장되기 때문에 map를 이터레이터로 순회하면 위의 순서, 즉 키의 정렬 순서로 이루어집니다.
#include <iostream> #include <string> #include <map> using namespace std; int main () { 하나의 간단한 예제를 보여 주어서 반전된 map의 첫 번째 요소를 가져오는 방법을 설명하겠습니다.1 map<int,int> m { 1, 10}, { 2, 20 }, { 3, 3= { 0 } };1auto ite = m .crbegin();1cout << "반전된 map 컨테이너 m 的第一个元素是:";-cout << "{" << ite >first << "", "-<< ite return 0; }
출력:
>second << "}\n";1반전된 map 컨테이너 m3, 30}의 첫 번째 요소는: {
위의 예제에서 crbegin() 함수는 반전된 map 컨테이너 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>::const_reverse_iterator rit; for (rit = marks.crbegin(); rit != marks.crend(); ++rit) cout << rit->first << " | " << rit->second << '\n'; auto ite = marks.crbegin(); cout << "\n최고점수는: " << ite->first << "\n"; cout << "Topper의 卷数는: " << ite->second << "\n"; return 0; }
출력:
점수 | 권고 번호 ______________________ 480 | 30 425 | 50 400 | 10 312 | 20 300 | 40 최고 점수는: 480 Topper의 권고 번호는: 30
위의 예제에서는 map 태그를 구현했습니다. '권고 번호(Roll Number)'를 값으로, 태그를 키로 저장합니다. 이를 통해 map의 자동 정렬 기능을 활용하고, 가장 높은 태그를 가진 권고 번호를 식별할 수 있습니다.