C++ STL 中 map crbegin() 和 crend() 函式


在本文中,我們將討論 C++ STL 中 map::crbegin() 和 map::crend() 函式的工作原理、語法和示例。

什麼是 C++ STL 中的 Map?

Map 是關聯容器,它可以方便地儲存由鍵值對組成的元素,並按特定順序排列。在 map 容器中,資料內部總是根據其關聯的鍵進行排序。map 容器中的值可以透過其唯一的鍵進行訪問。

什麼是 map::cbegin()?

map::crbegin() 函式是 C++ STL 中的內建函式,它在 header file. crbegin() implies constant reverse begin, means the reverse of the cbegin which was constant begin, in other words the function crbegin() will return the iterator which is pointing to the last element of the map container associated with the function. This iterator can’t be used to modify the map. This can be just used to traverse the set container.

語法

Map_name.crbegin();

引數

此函式不接受任何引數。

返回值

此函式返回一個迭代器,指向 map 容器的最後一個元素。

示例

輸入

map<char, int> newmap;
newmap[‘a’] = 1;
newmap[‘b’] = 2;
newmap[‘c’] = 3;
newmap.crbegin();

輸出

c:3

map::crbegin

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   map<int, int> TP_Map;
   TP_Map.insert({3, 50});
   TP_Map.insert({2, 30});
   TP_Map.insert({1, 10});
   TP_Map.insert({4, 70});
   //using map::crbegin to fetch first last element
   auto temp = TP_Map.crbegin();
   cout<<"First element is: "<<temp->first << " -> " << temp->second;
   cout<<"\nTP Map is : \n";
   cout << "MAP_KEY\tMAP_ELEMENT\n";
   for (auto i = TP_Map.crbegin(); i!= TP_Map.crend(); i++) {
      cout << i->first << "\t" << i->second << endl;
   }
   return 0;
}

輸出

First element is: 4 -> 70
TP Map is:
MAP_KEY    MAP_ELEMENT
4             70
3             50
2             30
1             10

什麼是 map::crend()?

map::crend() 函式是 C++ STL 中的內建函式,它在 `` 標頭檔案中定義。crend() 代表常量反向結束迭代器,這意味著它是常量結束迭代器 cend 的反向迭代器。換句話說,crend() 函式將返回一個迭代器,指向 map 容器中第一個位置之前的 position。此迭代器不能用於修改 map。它只能用於遍歷 map 容器。

語法

newmap.crend();

引數

此函式不接受任何引數。

返回值

它返回一個迭代器,指向關聯的 map 容器的第一個元素之前的位置。

示例

輸入

map<char, int> newmap;
newmap[‘a’] = 1;
newmap[‘b’] = 2;
newmap[‘c’] = 3;
newmap.crend();

輸出

error

map::crend

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   map<int, int> TP_Map;
   TP_Map.insert({3, 50});
   TP_Map.insert({2, 30});
   TP_Map.insert({1, 10});
   TP_Map.insert({4, 70});
   cout<<"\nTP Map is : \n";
   cout << "MAP_KEY\tMAP_ELEMENT\n";
   for (auto i = TP_Map.crbegin(); i!= TP_Map.crend(); i++) {
      cout << i->first << "\t" << i->second << endl;
   }
   return 0;
}

輸出

TP Map is:
MAP_KEY    MAP_ELEMENT
4             70
3             50
2             30
1             10

更新於:2020年4月15日

72 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.