How can I print out C++ map values?
我有一个这样的
1  | map<string, pair<string,string> > myMap;  | 
我在地图中插入了一些数据,使用:
1  | myMap.insert(make_pair(first_name, make_pair(middle_name, last_name)));  | 
现在如何打印出地图中的所有数据?
1 2 3 4 5 6  | for(map<string, pair<string,string> >::const_iterator it = myMap.begin(); it != myMap.end(); ++it) { std::cout << it->first <<"" << it->second.first <<"" << it->second.second <<" "; }  | 
在C++ 11中,你不需要拼出EDOCX1,0。您可以使用
1 2 3 4 5  | for(auto it = myMap.cbegin(); it != myMap.cend(); ++it) { std::cout << it->first <<"" << it->second.first <<"" << it->second.second <<" "; }  | 
注意使用
更简单的是,您可以使用基于范围的for循环:
1 2 3 4 5  | for(auto elem : myMap) { std::cout << elem.first <<"" << elem.second.first <<"" << elem.second.second <<" "; }  | 
如果你的编译器支持(至少部分)C++ 11,你可以做一些类似的事情:
1 2 3 4 5  | for (auto& t : myMap) std::cout << t.first <<"" << t.second.first <<"" << t.second.second <<" ";  | 
对于C++ 03,我使用EDCOX1,4,用插入操作符代替:
1 2 3 4 5 6 7 8 9  | typedef std::pair<string, std::pair<string, string> > T; std::ostream &operator<<(std::ostream &os, T const &t) { return os << t.first <<"" << t.second.first <<"" << t.second.second; } // ... std:copy(myMap.begin(), myMap.end(), std::ostream_iterator<T>(std::cout," "));  | 
由于C++ 17,可以使用基于范围的循环和结构化绑定来在地图上迭代。这提高了可读性,因为您减少了代码中所需的
1 2 3 4 5 6  | std::map<std::string, std::pair<std::string, std::string>> myMap; myMap["x"] = {"a","b" }; myMap["y"] = {"c","d" }; for (const auto &[k, v] : myMap) std::cout <<"m[" << k <<"] = (" << v.first <<"," << v.second <<")" << std::endl;  | 
输出:
m[x] = (a, b)
m[y] = (c, d)
科利鲁代码