English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C ++ map cbegin()函数用于返回指向map容器第一个元素的常量迭代器。
const_iterator cbegin() const noexcept; //C++ 11 之后
没有
它返回一个const_iterator,指向地图的第一个元素。
让我们来看一个简单的cbegin()函数示例。
#include <iostream> #include <map> using namespace std; int main () { map<char,string> mymap; mymap['b'] = "Java"; mymap['a'] = "C++"; mymap['c'] = "SQL"; // 显示内容: for (auto it = mymap.cbegin(); it != mymap.cend(); ++it) cout <<(*it).first << " => " << (*it).second << '\n'; return 0; }
Output:
a => C++ b => Java c => SQL
在上面,cbegin()函数用于返回一个常量迭代器,该迭代器指向mymap映射中的第一个元素。
让我们看一个简单的示例,使用for-each循环遍历地图。
#include <iostream> #include <map> #include <string> #include <iterator> #include <algorithm> using namespace std; int main() { map<string, int> m; m["Room1"] = 100; m["Room2"] = 200; m["Room3"] = 300; //使用std::for each和Lambda函数遍历一个map for_each(m.cbegin(), m.cend(), [](pair<string, int> element){ // 从元素访问KEY string word = element.first; // Accessing VALUE from element. int count = element.second; cout << word << " = " << count << endl; }); return 0; }
Output:
Room1 = 100 Room2 = 200 Room3 = 300
Nel seguente esempio, utilizziamo l'algoritmo STL std::for_each per esplorare la mappa. Itererà su ogni elemento della mappa e chiamerà il callback fornito.
Ecco un esempio semplice di come iterare su una mappa utilizzando un ciclo while.
#include <iostream> #include <map> #include <string> int main() { using namespace std; map<int,string> mymap = { { 100, "Nikita"}, { 200, "Deep" }}; { 300, "Priya" }, { 400, "Suman" }, { 500, "Aman" }}; map<int, string>::const_iterator it; // Dichiarazione di un iteratore it = mymap.cbegin(); // Assegna l'inizio dell'array while (it != mymap.cend()) { cout << it->first << " = " << it->second << "\n"; // Stampa il valore dell'elemento puntato ++it; // Esegue l'iterazione al successivo elemento } cout << endl; }
Output:
100: Nikita 200: Deep 300: Priya 400: Suman 500: Aman
Nel seguente esempio, la funzione cbegin() viene utilizzata per restituire un iteratore costante che punta al primo elemento del contenitore mymap.
Lasciate che vi mostri un altro esempio semplice.
#include <iostream> #include <string> #include <map> using namespace std; int main () { map<int,int> mymap = { { 10, 10 }, { 20, 20 }, { 30, 30 } }; cout << "元素是:" << endl; for (auto it = mymap.cbegin(); it != mymap.cend(); ++it) cout << it->first << " + " << it->second << " = " <<it->first + it->second << '\n'; auto ite = mymap.cbegin(); cout << "Il primo elemento è: "; cout << "{" << ite->first << ", " << ite->second << "}\n"; return 0; }
Output:
L'elemento è: 10 + 10 = 20 20 + 20 = 40 30 + 30 = 60 Il primo elemento è: {10, 10}
In esempio sopra, la funzione cbegin() viene utilizzata per restituire l'iteratore che punta al primo elemento del contenitore mymap.