繁体   English   中英

如何打印出 C++ map 值?

[英]How can I print out C++ map values?

我有一个像这样的map

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

我已经使用以下方法将一些数据插入到我的 map 中:

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

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

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()cbegin() cend()函数的使用。

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

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

如果您的编译器支持(至少部分)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"));

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 上的代码

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

然后通过使用从myMap.begin()myMap.end()的迭代器循环遍历 map 并将其打印出来,并打印出 map 中的键和值对,其中 it- it->first用于键,it- it->second用于值。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM