-1
我想写与全自动创建矢量没有给定大小的方法的载体类:的std :: istream的与运营商>>和自己的向量类
std::istream& operator >> (std::istream& is, Vector& v)
{
/* working (but not mine) version i am basing on
int size;
is >> size;
v.create(size);
for(int i=0; i<v.size(); i++) is >> v.m_pBuf[i];
return is;
*/
int size;
std::string strBuf;
//std::istream& tmp = is; //copy doesn't exist!
//is.ignore(0,'\n');
getline(is, strBuf,'\n');
size = (strBuf.length()+1)/2;
std::cout << "Size of buffer = " <<size<< std::endl;
std::cout << "bufrer = " <<strBuf<< std::endl;
v.create(size);
for(int i=0; i<v.size()*2; i++) {
if (!(i%2)){ // to avoid spaces
double vec = (double)strBuf[i]-48;
//std::cout << "vec = " <<vec<< std::endl;
v.m_pBuf[i]= vec;
}
}
return is;
}
,但它与一个错误崩溃:
/*
input:
Vector x(3);
x[0] = 1;
x[1] = 2;
x[2] = 3;
Vector y(x);
Vector z;
std::cout << "x=" << x << "y=" << y << "z=" << z;
std::cout << "Podaj wektor z: ";
std::cin >> z;
std::cout << "z=" << z;
output:
x=[ 1 2 3 ]
y=[ 1 2 3 ]
z=[ ]
Insert a vector z: 2 3 4 5 6 7
Size of buffer = 6
buffer = 2 3 4 5 6 7
z=[ 2 0 3 0 4 0 ]
Process returned -1073741819 (0xC0000005) execution time : 44.491 s
Press any key to continue.
*/
是否有任何技巧冻结我的'is'变量或重写输入流?这一切都是错的吗?
的代码来计算输入向量的大小将不会工作,如果你有比9大值或负值。 – 2015-02-24 14:50:35
至于你的问题,再次看看那个循环条件,并考虑它将循环多少次,因此写入'v.m_pBuf [i]'。还请阅读关于[*未定义的行为*](http://en.wikipedia.org/wiki/Undefined_behavior),例如,当您写入超出分配的内存限制时会发生。 – 2015-02-24 14:51:58
你是对的,谢谢。我会想另一个解决方案 – 2015-02-24 15:00:44