2015-02-24 30 views
-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'變量或重寫輸入流?這一切都是錯的嗎?

+0

的代碼來計算輸入向量的大小將不會工作,如果你有比9大值或負值。 – 2015-02-24 14:50:35

+1

至於你的問題,再次看看那個循環條件,並考慮它將循環多少次,因此寫入'v.m_pBuf [i]'。還請閱讀關於[*未定義的行爲*](http://en.wikipedia.org/wiki/Undefined_behavior),例如,當您寫入超出分配的內存限制時會發生。 – 2015-02-24 14:51:58

+0

你是對的,謝謝。我會想另一個解決方案 – 2015-02-24 15:00:44

回答

2

在您的for循環中,您基於i索引v.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. 
     } 
}