C++ STL 中 map 的 cbegin() 和 cend() 函式
在本文中,我們將討論 C++ STL 中 map::cbegin() 和 map::cend() 函式的工作原理、語法和示例。
什麼是 C++ STL 中的 Map?
Map 是關聯容器,它可以方便地按特定順序儲存由鍵值對組成的元素。在 map 容器中,資料內部始終透過其關聯的鍵進行排序。map 容器中的值透過其唯一的鍵進行訪問。
什麼是 map::cbegin()?
map::cbegin() function is an inbuilt function in C++ STL, which is defined in <map> header file. cbegin() is the constant begin function.
此函式返回一個指向 map 容器中第一個元素的常量迭代器。返回的迭代器是常量迭代器,不能用於修改內容。可以使用它們透過增加或減少迭代器來遍歷 map 容器中的元素。
語法
newmap.cbegin();
引數
此函式不接受任何引數。
返回值
它返回一個指向關聯 map 容器中第一個元素的迭代器。
示例
輸入
map<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() {
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::cbegin to fetch first element
auto temp = TP_Map.cbegin();
cout <<"First element is: "<<temp->first << " -> " << temp->second;
cout<<"\nTP Map is : \n";
cout << "MAP_KEY\tMAP_ELEMENT\n";
for (auto i = TP_Map.cbegin(); i!= TP_Map.cend(); i++) {
cout << i->first << "\t" << i->second << endl;
}
return 0;
}輸出
First element is: 1 -> 10 TP Map is: MAP_KEY MAP_ELEMENT 1 10 2 30 3 50 4 70
什麼是 map::cend()?
map::cend() 函式是 C++ STL 中的內建函式,定義在……
返回的迭代器是常量迭代器,不能用於修改內容,可以使用它們透過增加或減少迭代器來遍歷 map 容器中的元素。
map::cbegin() 和 map::cend() 用於透過給出範圍的開始和結束來遍歷整個容器。
語法
newmap.cend();
引數
此函式不接受任何引數。
返回值
它返回一個指向關聯 map 容器中最後一個元素之後的迭代器。
示例
輸入
map<char, int> newmap; newmap[‘a’] = 1; newmap[‘b’] = 2; newmap[‘c’] = 3; newmap.cend();
輸出
error
示例
#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.cbegin(); i!= TP_Map.cend(); i++) {
cout << i->first << "\t" << i->second << endl;
}
return 0;
}輸出
TP Map is: MAP_KEY MAP_ELEMENT 1 10 2 30 3 50 4 70
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP