C++ STL 中的 multimap::crbegin() 和 multimap::crend()
在本文中,我們將討論 C++ STL 中 multimap::crbegin() 和 multimap::crend() 函式的工作原理、語法和示例。
什麼是 C++ STL 中的 Multimap?
Multimap 是關聯容器,類似於 map 容器。它還可以以特定順序儲存由鍵值對和對映值組合而成的元素。在一個 multimap 容器中,可以有多個元素與同一個鍵關聯。資料在內部總是根據其關聯的鍵進行排序。
什麼是 multimap::cbegin()?
multimap::crbegin() 函式是 C++ STL 中的內建函式,它在 <map> 標頭檔案中定義。crbegin() 代表常量反向開頭,意味著它是 cbegin(常量開頭)的反向,換句話說,crbegin() 函式將返回指向與該函式關聯的 multimap 容器的最後一個元素的迭代器。此迭代器不能用於修改 multimap。它只能用於遍歷集合容器。
語法
mutliMap_name.crbegin();
引數
此函式不接受任何引數。
返回值
此函式返回指向容器最後一個元素的迭代器。
輸入
multimap<char, int> newmap; newmap(make_pair(‘a’, 1)); newmap(make_pair(‘b’, 2)); newmap(make_pair(‘c’, 3)); newmap.crbegin();
輸出
c:3
示例
#include <bits/stdc++.h>
using namespace std;
int main(){
//create the container
multimap<int, int> mul;
//insert using emplace
mul.emplace_hint(mul.begin(), 1, 10);
mul.emplace_hint(mul.begin(), 2, 20);
mul.emplace_hint(mul.begin(), 2, 30);
mul.emplace_hint(mul.begin(), 1, 40);
mul.emplace_hint(mul.begin(), 1, 50);
mul.emplace_hint(mul.begin(), 5, 60);
auto it = mul.crbegin();
cout<<"Last element using crbegin() is: {"<<it->first<< ", " << it->second << "}\n";
cout <<"\nElements in multimap is : \n";
cout << "KEY\tELEMENT\n";
for (auto i = mul.crbegin(); i!= mul.crend(); i++){
cout << i->first << "\t" << i->second << endl;
}
return 0;
}輸出
如果我們執行上面的程式碼,它將生成以下輸出:
Last element using crbegin() is: {5, 60}
Elements in multimap is :
KEY ELEMENT
5 60
2 20
2 30
1 10
1 40
1 50什麼是 multimap::crend()?
multimap::crend() 函式是 C++ STL 中的內建函式,它在 <map> 標頭檔案中定義。crend() 代表常量反向結束迭代器,意味著它是 cend(常量結束迭代器)的反向,換句話說,crend() 函式將返回指向與該函式關聯的容器的第一個位置之前的迭代器。此迭代器不能用於修改 multimap。它只能用於遍歷 multimap 容器。
語法
newmultimap.crend();
引數
此函式不接受任何引數。
返回值
它返回一個指向關聯容器的第一個元素之前的迭代器。
輸入
multimap<char, int&lgt; newmap; newmap(make_pair(‘a’, 1)); newmap(make_pair(‘b’, 2)); newmap(make_pair(‘c’, 3)); newmap.crend();
輸出
error
示例
#include <bits/stdc++.h>
using namespace std;
int main(){
//create the container
multimap<int, int> mul;
//insert using emplace
mul.emplace_hint(mul.begin(), 1, 10);
mul.emplace_hint(mul.begin(), 2, 20);
mul.emplace_hint(mul.begin(), 2, 30);
mul.emplace_hint(mul.begin(), 1, 40);
mul.emplace_hint(mul.begin(), 1, 50);
mul.emplace_hint(mul.begin(), 5, 60);
cout << "\nElements in multimap is : \n";
cout << "KEY\tELEMENT\n";
for (auto i = mul.crbegin(); i!= mul.crend(); i++){
cout <<<; i->first << "\t" << i->second < endl;
}
return 0;
}輸出
如果我們執行上面的程式碼,它將生成以下輸出:
Elements in multimap is : KEY ELEMENT 5 60 2 20 2 30 1 10 1 40 1 50
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP