0

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?

BoBTFish
  • 19,167
  • 3
  • 49
  • 76
mooky Fare
  • 87
  • 5
  • 1
    [This shows how to define an **input** operator for a `std::pair`](https://stackoverflow.com/a/30642290/1171191). You need an **output** operator, but the same special conditions apply. – BoBTFish May 13 '18 at 07:58
  • 1
    Consider using `std::vector` instead of `std::list`. It wil generally perform much better on modern hardware. – Jesper Juhl May 13 '18 at 10:17

1 Answers1

4

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;

}
DimChtz
  • 4,043
  • 2
  • 21
  • 39