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.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...