加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:56:20 所属栏目:百科 来源:网络整理
导读:我已经声明一个运算符 for std :: pair int,intgt ;: std::ostream operator(std::ostream o,const std::pairint,int p) { o p.first p.second; return o;} 当我打印我的数据时,我想使用这个操作符: std::vectorstd::pairint,int data;std::copy(data.begin
我已经声明一个运算符<< 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读