C++ multimap cbegin() 函数
C++ 的 multimap cbegin() 函数用于返回指向 multimap 容器中第一个元素的常量迭代器。
语法
const_iterator cbegin() const noexcept; //since C++ 11
const_iterator 是指向常量内容的迭代器。
参数
无
返回值
它返回一个指向multimap第一个元素的const_iterator。
复杂度
常量时间复杂度
迭代器有效性
无更改
数据竞争
容器被访问
异常安全性
该成员函数不会抛出异常
示例1
让我们来看看cbegin()函数的简单示例:
#include <iostream>
#include <map>
using namespace std;
int main ()
{
multimap<char,string> mymultimap;
mymultimap = {
{'a',"Java"},
{'b', "C++"},
{'b', "Python"},
{'a', "Android"}
};
// show content:
for (auto it = mymultimap.cbegin(); it != mymultimap.cend(); ++it)
cout <<(*it).first << " => " << (*it).second << '\n';
return 0;
}
输出:
a => Java
a => Android
b => C++
b => Python
在上面的示例中,cbegin()函数被用于返回一个指向mymultimap multimap中第一个元素的const_iterator。
示例2
让我们看一个简单的示例,使用for-each循环迭代multimap:。
#include <iostream>
#include <map>
#include <string>
#include <iterator>
#include <algorithm>
using namespace std;
int main() {
multimap<string, int> m;
m= {
{"Room1", 100},
{"Room2", 200},
{"Room1", 300},
{"Room1", 100}
};
// Iterate over a multimap using std::for_each and Lambda function
for_each(m.cbegin(), m.cend(),
[](pair<string, int> element){
// Accessing KEY from element
string word = element.first;
// Accessing VALUE from element.
int count = element.second;
cout<<word<<" = "<<count<<endl;
});
return 0;
}
输出:
Room1 = 100
Room1 = 300
Room1 = 100
Room2 = 200
在上面的示例中,我们使用STL算法std::for-each来迭代遍历multimap。它将遍历每个multimap元素,并调用我们提供的回调函数。
示例3
让我们看一个使用while循环遍历multimap的简单示例:
#include <iostream>
#include <map>
#include <string>
int main()
{
using namespace std;
multimap<int,string> mymultimap = {
{ 100, "Nikita"},
{ 200, "Deep" },
{ 300, "Priya" },
{ 200, "Suman" },
{ 400, "Aman" }};
multimap<int, string>::const_iterator it; // declare an iterator
it = mymultimap.cbegin(); // assign it to the start of the multimap
while (it != mymultimap.cend()) // while it hasn't reach the end
{
cout << it->first << " = " << it->second << "\n";
// print the value of the element it points to
++it; // and iterate to the next element
}
cout << endl;
}
输出:
100 = Nikita
200 = Deep
200 = Suman
300 = Priya
400 = Aman
在上面的示例中,cbegin()函数用于返回一个const_iterator,指向mymultimap multimap的第一个元素。
示例4
让我们看另一个简单的示例:
#include <map>
#include <iostream>
int main()
{
using namespace std;
multimap <int, int> m1;
multimap <int, int> :: iterator m1_Iter;
multimap <int, int> :: const_iterator m1_cIter;
typedef pair <int, int> Int_Pair;
m1.insert ( Int_Pair ( 0, 0 ) );
m1.insert ( Int_Pair ( 1, 1 ) );
m1.insert ( Int_Pair ( 2, 4 ) );
m1_cIter = m1.cbegin ();
cout << "The first element of m1 is " << m1_cIter -> first << endl;
m1_Iter = m1.begin ();
m1.erase ( m1_Iter );
// The following 2 lines would err as the iterator is const
// m1_cIter = m1.begin ();
// m1.erase ( m1_cIter );
m1_cIter = m1.cbegin();
cout << "First element of m1 is now " << m1_cIter -> first << endl;
}
输出:
The first element of m1 is 0
First element of m1 is now 1
在上面的示例中,cbegin()函数用于返回指向mymultimap multimap中第一个元素的const_iterator。