映射是关联容器,以映射方式存储元素。每个元素都有一个键值和一个映射值。任何两个映射值都不能具有相同的键值。
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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。