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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With