映射是關聯容器,以映射方式存儲元素。每個元素都有一個鍵值和一個映射值。任何兩個映射值都不能具有相同的鍵值。
map::begin()
begin()函數用於返回指向Map容器第一個元素的迭代器。 begin()函數將雙向迭代器返回到容器的第一個元素。
用法:
mapname.begin() 參數: No parameters are passed. 返回: This function returns a bidirectional iterator pointing to the first element.
例子:
Input :mymap['a'] = 1; mymap['b'] = 2; mymap['c'] = 3; mymap.begin(); Output:returns an iterator to the element 'a' = 1 Input :mymap['d'] = 1; mymap.begin(); Output:returns an iterator to the element 'd' = 1
錯誤和異常
1.它沒有異常拋出保證。
2.傳遞參數時顯示錯誤。
// Demonstrates begin() and end()
#include <iostream>
#include <map>
using namespace std;
int main()
{
// declaration of map container
map<char, int> mymap;
mymap['a'] = 1;
mymap['b'] = 2;
mymap['c'] = 3;
// using begin() to print map
for (auto it = mymap.begin();
it != mymap.end(); ++it)
cout << it->first << " = "
<< it->second << '\n';
return 0;
}
輸出:
a = 1 b = 2 c = 3
map::end()
end()函數用於返回指向過去Map容器最後一個元素的迭代器。由於它不引用有效元素,因此無法取消引用end()函數將返回雙向迭代器。
用法:
mapname.end() 參數: No parameters are passed. 返回: This function returns a bidirectional iterator pointing to the next of last element.
例子:
Input :mymap['a'] = 1; mymap['b'] = 2; mymap['c'] = 3; mymap.end(); Output:returns an iterator to next to c (after last element)
錯誤和異常
1.它沒有異常拋出保證。
2.傳遞參數時顯示錯誤。
// CPP program to illustrate
// Demonstrates begin() and end()
#include <iostream>
#include <map>
using namespace std;
int main()
{
// declaration of map container
map<char, int> mymap;
mymap['a'] = 1;
mymap['b'] = 2;
mymap['c'] = 3;
// using begin() to print map
for (auto it = mymap.begin();
it != mymap.end(); ++it)
cout << it->first << " = "
<< it->second << '\n';
return 0;
}
輸出:
a = 1 b = 2 c = 3
相關用法
注:本文由純淨天空篩選整理自AyushSaxena大神的英文原創作品 map::begin() and end() in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。