mooky Fare
mooky Fare

Reputation: 97

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

I define a lists like this:

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

I want to print out all list elements, so I write it out:

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

But I've been getting this error:

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

in Visual Studio. How can I fix it,or is there any other way to print out all pairs in a list?

Upvotes: 0

Views: 1302

Answers (1)

DimChtz
DimChtz

Reputation: 4333

You 're getting this error because there is no overloaded operator << for std::pair.

However, printing a list of pairs is not that hard. I don't know if this is an elegant way to print all pairs in a list but all you need is a simple for loop:

#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;

}

Upvotes: 4

Related Questions