【问题标题】:How can I print out C++ map values?如何打印出 C++ 映射值?
【发布时间】:2012-12-13 19:16:42
【问题描述】:

我有一个这样的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


【解决方案1】:
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&lt;string, pair&lt;string,string&gt; &gt;::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";
}

【讨论】:

  • 最后一个不慢吗?
  • @Paul:我将其编辑为const auto&amp; 以避免复制元素。希望这就是你的意思。除此之外,不,最后一个不慢
【解决方案2】:

如果您的编译器支持(至少部分)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&amp; t : myMap) std::cout &lt;&lt; t.first &lt;&lt; " " &lt;&lt; t.second.first &lt;&lt; " " &lt;&lt; t.second.second &lt;&lt; "\n";
  • 使用引用 &amp; 避免在循环迭代期间进行复制。
【解决方案3】:

由于C++17,您可以使用range-based for loopsstructured bindings 来迭代您的地图。这提高了可读性,因为您减少了代码中所需的 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)

Code on Coliru

【讨论】:

  • 好更新!您可能希望将参数作为 for 循环中的 const 引用。
  • 当我尝试执行 for 循环时,我得到“标识符“k”未定义。”
  • @AlphaFoxtrot:你真的为 C++17 编译过它吗?正如您从 Coliru 的链接中看到的那样,代码实际上正在运行。
  • 啊,我明白了。我最近下载了 Visual Studio,我认为它会让我获得最新的。原来我使用的是 C++98。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-31
  • 1970-01-01
  • 2021-04-13
  • 1970-01-01
  • 1970-01-01
  • 2013-11-23
  • 1970-01-01
相关资源
最近更新 更多