C++,对自定义的类型用istream_iterator出错!

来源:百度知道 编辑:UC知道 时间:2024/05/29 03:30:30
程序如下:
#include<stdafx.h>
#include<iostream>
#include<algorithm>
#include<iterator>
#include<vector>

class Node /*自定义的类,只有两个整型成员*/
{
public:
int x,y;

Node() {}
Node(int xx,int yy):x(xx),y(yy) {}
/*输入输出*/
friend std::ostream& operator<<(std::ostream&,Node&);
friend std::istream& operator>>(std::istream&,Node&);
};
std::ostream& operator<<(std::ostream& out,Node& n)
{
out<<n.x<<','<<n.y;
return out;
}
std::istream& operator>>(std::istream& in,Node& n)
{
in>>n.x>>n.y;
return in;
}

int main()
{
std::vector<Node> vn;
/*用istream_iterator输入一批Node*/
std::copy(std::istream_iterator<Node>(std::cin),std::istream_iterator<Node>(),std::back_inserter(vn));
/*用ostream_iterator输出一批Node*/
std::copy(vn.

楼上说的不错,那种更改能使编译器闭嘴
但是还有一种更改
std::ostream& operator<<(std::ostream& out, Node n)也能使编译器闭嘴
可见他的理由不是很充分,但是他的建议值得你去实行!
当一个函数中的参数在调用过程中不改变其值,就尽量用 const type& 来替换 type ,注意这里的type最好是自定义类型,因为内置类型int double用第二种更快!第一种少了赋值,直接拿来用(在不改变其内容的前提下),第二种是复制,你用vector,应该知道复制一个vector(元素比较多的情况下)的开销不小,const type& 就有利用的价值,而在内置类型的情况下,const type& 的实现过程要比一个简单的复制复杂,所以影响效率。但是很多人为了编程习惯的一致性,第二种也用 const type& (const int&...)等,其实也没什么,都可以的,影响非常小。
至于什么时候用引用 type&
恰好与上面的相反:当你想改变某个对象的值是用type &(如swap()函数(交换函数)中就最好用引用(非常量)而不是指针,cin中也是)
好了这个问题就说到这!
下来就说为什么编译器从上面的程序中扑捉到了一条错误,确切的说问题出在std::copy()上,任何algorithm中的函数都是用迭代实现的(循环,从第一个参数(起点迭代)到第二个参数(终点后迭代),其他的参数就不说了(可能还是迭代器),copy()是非改变性算法(不改变迭代所指的值)所以copy中迭代器其的类型是const_iterator(const_reverse_iterator),不能改变引用的原值。
你用常量引用(const type&)或者type作为参数类型都能够通过编译
{另外,还有一种迭代器类型就是iterator(reverse_iterator)它允许改变所指元素,但是copy()无福消受,呵呵!,你用引用或指针作为参数类型就行了}
很明显
std::ostream& operator<<(std::ostream&,Node&);
这里用了引用(允许改变所指的值)就违反了copy