C ++:打印列表中所有对的优雅方式

时间:2018-05-13 07:47:11

标签: c++ list stl std-pair

我定义了这样的列表:

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中

。我该如何修复它,或者是否有其他方法可以打印列表中的所有对?

1 个答案:

答案 0 :(得分:3)

您收到此错误是因为operator <<没有超载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;

}