Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::ostream_iterator does not find operator<<

I have declared an operator<< for std::pair<int, int>:

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

I want to use this operator when i print my data:

std::vector<std::pair<int, int>> data;
std::copy(data.begin(), data.end(), std::ostream_iterator<std::pair<int, int>>(std::cout, "\n"));

But the compiler says, no match for operator<< ... What am i doing wrong?

like image 499
WonderCsabo Avatar asked Nov 29 '13 11:11

WonderCsabo


1 Answers

std::copy cannot find overloading for operator << for std::pair in std namespace. There is no good way, to overload operator << for object from std namespace in algorithms from std namespace.

You can use std::for_each with functor, that will print your values, for example with lambda.

std::for_each(data.begin(), data.end(), [](const std::pair<int, int>& p)
{
   std::cout << p << std::endl;
});

You cannot put overloading in std namespace, you can only add specializations for user-defined types since

The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified

A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.

like image 94
ForEveR Avatar answered Oct 06 '22 22:10

ForEveR