我如何打印出c++映射值

How can I print out C++ map values?

本文关键字:c++ 映射 打印 何打印      更新时间:2023-10-16

我有一个这样的map:

map<string, pair<string, string>> myMap;

我已经插入了一些数据到我的地图使用:

myMap.insert(make_pair(first_name, make_pair(middle_name, last_name)));

我现在如何打印出地图中的所有数据?

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 << "n";
}

在c++ 11中,您不需要拼写map<string, pair<string,string> >::const_iterator。您可以使用auto

for(auto it = myMap.cbegin(); it != myMap.cend(); ++it)
{
    std::cout << it->first << " " << it->second.first << " " << it->second.second << "n";
}

注意cbegin()cend()函数的使用。

更简单,您可以使用基于范围的for循环:

for(const auto& elem : myMap)
{
   std::cout << elem.first << " " << elem.second.first << " " << elem.second.second << "n";
}

从c++ 17开始,你可以使用基于范围的for循环和结构化绑定来迭代你的映射。这提高了可读性,因为您减少了代码中所需的firstsecond成员的数量:

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)

Coliru代码

如果你的编译器支持c++ 11,你可以这样做:

for (auto& t : myMap)
    std::cout << t.first << " " 
              << t.second.first << " " 
              << t.second.second << "n";

对于c++ 03,我将使用std::copy和插入操作符来代替:

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, "n"));

您可以尝试基于范围的循环像这样:

for(auto& x:myMap){
        cout<<x.first<<" "<<x.second.first<<" "<<x.second.second<<endl;
}

最简单的方法是首先将迭代器声明为
map<string ,string> :: iterator it;

,然后使用迭代器从myMap.begin()遍历映射到myMap.end(),打印出映射中的键和值对,其中键为it->first,值为it->second

  map<string ,string> :: iterator it;
    for(it=myMap.begin();it !=myMap.end();++it)
      {
       std::cout << it->first << ' ' <<it->second;
      }