C ++ map cend()函數(shù)用于返回常量迭代器,該常量迭代器位于map中的最后一個元素旁邊。
const_iterator cend() const noexcept; //從 C++ 11 開始
沒有
它返回一個常量迭代器,指向map的最后一個元素。
我們來看一個簡單的cend()函數(shù)示例。
#include <iostream>
#include <map>
using namespace std;
int main ()
{
map<char,int> mymap;
mymap['b'] = 100;
mymap['a'] = 200;
mymap['c'] = 300;
//打印內(nèi)容:
cout << "mymap contains:";
for (auto it = mymap.cbegin(); it != mymap.cend(); ++it)
cout << " [" << (*it).first << ':' << (*it).second << ']';
cout << '\n';
return 0;
}輸出:
打印內(nèi)容: [a:200] [b:100] [c:300]
在上面的示例中,cend()函數(shù)用于返回指向mymap 容器中最后一個元素旁邊的迭代器。
讓我們看一個簡單的示例,使用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)建一個map迭代器并指向映射的開始
map<string, int>::iterator it = m.begin();
// 對每個和Lambda函數(shù)使用std::迭代map
for_each(m.cbegin(), m.cend(),
[](pair<string, int> element){
// 從元素訪問KEY
string word = element.first;
//從元素訪問VALUE。
int count = element.second;
cout<<word<<" = "<<count<<endl;
});
return 0;
}輸出:
Room1 = 100 Room2 = 200 Room3 = 300
在上面的示例中,我們使用STL算法std :: for-each遍歷map。它將在每個map元素上進(jìn)行迭代,并調(diào)用我們提供的回調(diào)。
讓我們看一個使用while循環(huán)迭代map的簡單示例。
#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; // 聲明一個迭代器
it = mymap.cbegin(); //將其分配給向量的開頭
while (it != mymap.cend())
{
cout << it->first << " = " << it->second << "\n";
// 打印它所指向的元素的值
++it; // 并迭代到下一個元素
}
cout << endl;
}輸出:
100 = Nikita 200 = Deep 300 = Priya 400 = Suman 500 = Aman
在上面的示例中,cend()函數(shù)用于返回指向mymap容器中最后一個元素旁邊的常量迭代器。
讓我們看一個簡單的實(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.cbegin(); it != mymap.cend(); ++it)
cout << it->first
<< " + "
<< it->second
<< " = "
<<it->first + it->second
<< '\n';
auto ite = mymap.cend();
cout << "結(jié)束元素(指向最后一個): ";
cout << "{" << ite->first << ", "
<< ite->second << "}\n";
return 0;
}輸出:
元素是:
10 + 10 = 20
20 + 20 = 40
30 + 30 = 60
結(jié)束元素(指向最后一個): {3, 0}在上面的示例中,cend()函數(shù)用于返回指向mymap容器中最后一個元素旁邊的常量迭代器。