【问题标题】:C++:An elegant way to print all pairs in a listC++:打印列表中所有对的优雅方式
【发布时间】:2018-10-23 03:28:48
【问题描述】:

我这样定义一个列表:

std::list < pair<string, int> > token_list;

我想打印出所有列表元素,所以我把它写出来:

std::copy(std::begin(token_list),
          std::end(token_list),
          std::ostream_iterator<pair<string, int> >(std::cout, " "));

但我一直收到此错误:

error 2679:binary "<<"the operator (or unacceptable conversion) that accepts the right operand oftype (or unacceptable)

在 Visual Studio 中。我该如何解决它,或者有没有其他方法可以打印出列表中的所有对?

【问题讨论】:

标签: c++ list stl std-pair


【解决方案1】:

您收到此错误是因为 operator &lt;&lt; 没有为 std::pair 重载。

但是,打印成对列表并不难。我不知道这是否是 elegant way to print all pairs in a list,但您只需要一个简单的 for 循环:

#include <iostream>
#include <list>
#include <string>

int main() {

    std::list<std::pair<std::string, int>> token_list = { {"token0", 0}, {"token1", 1}, {"token2", 2} };

    for ( const auto& token : token_list )
        std::cout << token.first << ", " << token.second << "\n";

    return 0;

}

【讨论】:

  • 您不必要地复制了该循环中的所有对。使用for (const auto&amp; token : token_list)
  • @JesperJuhl 是的,已修复。
猜你喜欢
  • 1970-01-01
  • 2015-08-10
  • 2014-03-30
  • 1970-01-01
  • 2020-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多