C ++ map begin()函數(shù)用于返回引用map容器第一個(gè)元素的迭代器。
iterator begin(); //until C++ 11 const_iterator begin() const; //until C++ 11 iterator begin() noexcept; //since C++ 11 const_iterator begin() const noexcept; //since C++ 11
沒(méi)有
它返回一個(gè)指向map第一個(gè)元素的迭代器。
我們來(lái)看一個(gè)begin()函數(shù)的簡(jiǎn)單示例。
#include <iostream>
#include <map>
using namespace std;
int main ()
{
map<char,string> mymap;
mymap['b'] = "Java";
mymap['a'] = "C++";
mymap['c'] = "SQL";
// 展示內(nèi)容
for (map<char,string>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
cout << it->first << " => " << it->second << '\n';
return 0;
}輸出:
a => C++ b => Java c => SQL
在上面的代碼中,begin()函數(shù)用于返回指向mymap映射中第一個(gè)元素的迭代器。
讓我們看一個(gè)簡(jiǎn)單的示例,使用for-each循環(huán)遍歷map。
#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;
// 創(chuàng)建一個(gè)map迭代器并指向map的開(kāi)頭
map<string, int>::iterator it = m.begin();
// 使用std::for each和Lambda函數(shù)遍歷一個(gè)Map
for_each(m.begin(), m.end(),[](pair<string, int> element){
// 從元素訪問(wèn)KEY
string word = element.first;
// 從元素訪問(wèn)VALUE。
int count = element.second;
cout<<word<<" = "<<count<<endl;
});
return 0;
}輸出:
Room1 = 100 Room2 = 200 Room3 = 300
在上面的示例中,我們使用STL算法std :: for-each遍歷地圖。它將在每個(gè)map元素上進(jìn)行迭代,并調(diào)用我們提供的回調(diào)。
讓我們看一個(gè)使用while循環(huán)迭代地圖的簡(jiǎn)單示例。
#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" }};
cout<<"Elements are:" <<endl;
map<int, string>::const_iterator it; // 聲明一個(gè)迭代器
it = mymap.begin(); // 把它賦給向量的起點(diǎn)
while (it != mymap.end())
{
cout << it->first << " = " << it->second << "\n";
// 打印它所指向的元素的值
++it; // 并迭代到下一個(gè)元素
}
cout << endl;
}輸出:
Elements are: 100: Nikita 200: Deep 300: Priya 400: Suman 500: Aman
在上面的代碼中,begin()函數(shù)用于返回指向mymap映射中第一個(gè)元素的迭代器。
讓我們看一個(gè)簡(jiǎn)單的實(shí)例:
#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.begin(); it != mymap.end(); ++it)
cout << it->first
<< " + "
<< it->second
<< " = "
<<it->first + it->second
<< '\n';
auto ite = mymap.begin();
cout << "The first element is: ";
cout << "{" << ite->first << ", "
<< ite->second << "}\n";
return 0;
}輸出:
元素是:
10 + 10 = 20
20 + 20 = 40
30 + 30 = 60
The first element is: {10, 10}在上面的示例中,begin()函數(shù)用于返回指向mymap容器中第一個(gè)元素的迭代器。