微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – std :: ostream_iterator没有找到operator <<

我已经声明一个运算符<< for std :: pair< int,int&gt ;:
std::ostream& operator<<(std::ostream& o,const std::pair<int,int>& p) {
    o << p.first << p.second;
    return o;
}

当我打印我的数据时,我想使用这个操作符:

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

但编译器说,操作符<< ...
我究竟做错了什么?

解决方法

std :: copy找不到运算符<<在std命名空间中的std :: pair.没有好的方法,要超载运算符<来自std命名空间的算法中的std命名空间中的对象. 您可以使用std :: for_each与函子,这将打印您的值,例如使用lambda.
std::for_each(data.begin(),[](const std::pair<int,int>& p)
{
   std::cout << p << std::endl;
});

您不能在std命名空间中重载,您只能为自定义类型添加特殊化

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.

原文地址:https://www.jb51.cc/c/113272.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐