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

C++:An elegant way to print all pairs in a list

本文关键字:打印 方式 列表 一种 C++      更新时间:2023-10-16

我定义了一个这样的列表:

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中。我该如何修复它,或者有没有其他方法可以打印出列表中的所有对?

您收到此错误是因为没有std::pair的重载operator <<

但是,打印对列表并不难。我不知道这是否是一个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;
}