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"变量或重写输入流吗?这里到底出了什么问题?

在for循环中,基于iv.m_pBuf进行索引,其中跳过所有奇数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.
        }
}

最新更新