Question

I am trying to use ostream_iterator for writing a vector of pairs to a file.ostream_iterator requires a template argument to be applied at the time of declaration. The vector is defined as-

vector<pair<string,long>> test;

When I pass pair as a template to the ostream_iterator it shows an error -

Error 1 error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const std::pair<_Ty1,_Ty2>' (or there is no acceptable conversion) C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\iterator 531 1 wordsegmentation

What could be the correct argument in this situation?

Edit- Code Snippet

vector<pair<string,long>> t;
......
//t is filled up with elements 
ostream_iterator<pair<string,long>> output_iterator(out, "\n");
std::copy(t.begin(), t.end(), output_iterator);
Was it helpful?

Solution

There is NO operator << for std::pair. You cannot simply use ostream_iterator with std::pair.

You can use other things, or write class, that derived from pair, or that store pair and use it. You cannot write overloads in std namespace, since it leads to undefined behaviour and you cannot overload this operator in global namespace, since ADL will not find correct overload (if you use stl algorithms, like copy, ostream_iterator).

Simply, something like this will work well

#include <iostream>
#include <utility>
#include <algorithm>
#include <iterator>

int main()
{
   std::vector<std::pair<int, int>> vec =
   {
      {1,1},
      {2,2}
   };
   for (const auto& p : vec)
   {
      std::cout << p.first << " " << p.second << std::endl;
   }
}

OTHER TIPS

You can simply overload std::ostream& operator<<:

std::ostream& operator<<(std::ostream& o, const pair<string,long>& p)
{
  return o << p.first << " " << p.second;
}

Or have a look at pretty print C++ containers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top