C++ STL 中的 multimap::cbegin() 和 multimap::cend()
在本文中,我們將討論 C++ STL 中 multimap::cbegin() 和 multimap::cend() 函式的工作原理、語法和示例。
什麼是 C++ STL 中的 Multimap?
Multimap 是關聯容器,類似於 map 容器。它還便於以特定順序儲存由鍵值和對映值組合而成的元素。在一個 multimap 容器中,可以有多個元素與同一個鍵關聯。資料在內部始終藉助其關聯的鍵進行排序。
什麼是 multimap::cbegin()?
multimap::cbegin() 函式是 C++ STL 中的內建函式,它在 <map> 標頭檔案中定義。cbegin() 是常量開始函式。此函式返回指向 multimap 容器中第一個元素的常量迭代器。返回的迭代器是常量迭代器,它們不能用於修改內容。我們可以使用它們透過增加或減少迭代器來遍歷對映容器中的元素。
語法
multi.cbegin();
引數
此函式不接受任何引數。
返回值
它返回一個指向關聯的 map 容器中第一個元素的迭代器。
輸入
multimap<char, int> newmap; newmap[‘a’] = 1; newmap[‘b’] = 2; newmap[‘c’] = 3; newmap.cbegin();
**輸出** -
a = 1
示例
#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.cbegin();
cout << "First element in the multimap is: ";
cout << "{" << it->first << ", " << it->second << "}\n";
cout << "\nElements in multimap is : \n";
cout << "KEY\tELEMENT\n";
for (auto i = mul.cbegin(); i!= mul.cend(); i++){
cout << i->first << "\t" << i->second << endl;
}
return 0;
}輸出
如果我們執行以上程式碼,它將生成以下輸出 -
First element in the multimap is: {1, 50}
Elements in multimap is :
KEY ELEMENT
1 50
1 40
1 10
2 30
2 20
5 60什麼是 multimap::cend()?
multimap::cend() 函式是 C++ STL 中的內建函式,它在 <map> 標頭檔案中定義。cend() 函式是常量結束 ()。此函式返回關聯的 multimap 容器中最後一個元素之後的元素的常量迭代器。
返回的迭代器是常量迭代器,它們不能用於修改內容。我們可以使用它們透過增加或減少迭代器來遍歷對映容器中的元素。
multimap::cbegin() 和 multimap::cend() 用於透過提供範圍的開始和結束來遍歷整個容器。
語法
multi.cend();
引數
此函式不接受任何引數。
返回值
它返回一個指向關聯的 map 容器中最後一個元素之後的迭代器。
**輸入** -
multimap <char, int> newmap; newmap(make_pair(‘a’, 1)); newmap(make_pair(‘b’, 2)); newmap(make_pair(‘c’, 3)); newmap.cend();
**輸出** -
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.cbegin(); i!= mul.cend(); i++){
cout << i->first << "\t" << i->second << endl;
}
return 0;
}輸出
如果我們執行以上程式碼,它將生成以下輸出 -
Elements in multimap is : KEY ELEMENT 1 50 1 40 1 10 2 30 2 20 5 60
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP