是否可以访问map
中的元素而不迭代for(std::map
循环?
#include <iostream>
#include <vector>
#include <map>
int main()
{
std::vector<std::map<std::string, int>> v;
for (auto ii = 0; ii < 3; ii++)
{
std::map<std::string, int> _map;
_map["type"] = ii;
v.push_back(_map);
}
for(auto elem : v)
{
std::cout << elem["type"];
for(std::map<std::string, int>::iterator it = elem.begin(); it != elem.end(); ++it)
{
std::cout << " Keys: " << it->first << std::endl;
}
}
return 0;
}
输出:
0 Keys: type
1 Keys: type
2 Keys: type
可以用一种不那么冗长的方式:
std::map<std::string, int> m;
m["t1"]=1;
m["t2"]=2;
m["t3"]=3;
for(auto pair: m){
std::cout << pair.first << ": " << pair.second << std::endl;
}