如何打印出 C++ 映射值?

问题描述 投票:0回答:5

我有一个像这样的

map

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

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

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

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

c++ dictionary for-loop printing std-pair
5个回答
121
投票
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";
}

31
投票

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

31
投票

C++17 起,您可以使用 range-based for loopsstructured bindings 迭代你的地图。这提高了可读性,因为您减少了代码中所需的

first
second
成员的数量:

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


1
投票

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

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

0
投票

最简单的方法是先声明一个迭代器为

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;
      }
© www.soinside.com 2019 - 2024. All rights reserved.