C ++ map cend()函数用于返回常量迭代器,该常量迭代器位于map中的最后一个元素旁边。
const_iterator cend() const noexcept; //从 C++ 11 开始
没有
它返回一个常量迭代器,指向map的最后一个元素。
我们来看一个简单的cend()函数示例。
#include <iostream>
#include <map>
using namespace std;
int main ()
{
map<char,int> mymap;
mymap['b'] = 100;
mymap['a'] = 200;
mymap['c'] = 300;
//打印内容:
cout << "mymap contains:";
for (auto it = mymap.cbegin(); it != mymap.cend(); ++it)
cout << " [" << (*it).first << ':' << (*it).second << ']';
cout << '\n';
return 0;
}输出:
打印内容: [a:200] [b:100] [c:300]
在上面的示例中,cend()函数用于返回指向mymap 容器中最后一个元素旁边的迭代器。
让我们看一个简单的示例,使用for-each循环遍历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;
// 创建一个map迭代器并指向映射的开始
map<string, int>::iterator it = m.begin();
// 对每个和Lambda函数使用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元素上进行迭代,并调用我们提供的回调。
让我们看一个使用while循环迭代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()函数用于返回指向mymap容器中最后一个元素旁边的常量迭代器。
让我们看一个简单的实例。
#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 << "结束元素(指向最后一个): ";
cout << "{" << ite->first << ", "
<< ite->second << "}\n";
return 0;
}输出:
元素是:
10 + 10 = 20
20 + 20 = 40
30 + 30 = 60
结束元素(指向最后一个): {3, 0}在上面的示例中,cend()函数用于返回指向mymap容器中最后一个元素旁边的常量迭代器。