我正在尝试使用一种方法编写一个矢量类,该方法可以自动创建一个没有给定大小的矢量:
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'变量或重写输入流?这有什么不对的?
答案 0 :(得分:2)
在for循环中,您根据v.m_pBuf
索引i
,其中您跳过所有奇数i
。因此,您正在尝试访问位置0, 2, 4, ...
,这意味着您将超过分配的空间。尝试使用不同的索引变量并在if
条件内增加它。
您的代码如下所示:
for( int i=0, j=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[j]= vec;
j++; // notice j increments only for even positions.
}
}