2011-01-21 49 views
1

我有一個程序,只是像這樣添加兩個向量v1和v2:v1 + = v2。在每次迭代中,v2都被添加到v1中。考慮下面的程序:矢量的怪異行爲?

#include <iostream> 
    #include <vector> 
    #include <iterator> 

    using namespace std; 

    typedef vector<double> v_t; 

    int main(){ 

    v_t v1; 
    v_t v2; 

    for (int i = 1; i<10; i++){ 
     v1.push_back(i); 
     v2.push_back(i); 
     if (i == 5){   // Just want to insert a 0 inbetween 
     v1.push_back(0); 
     v2.push_back(0); 
     } 
    } 

// v1 : 1 2 3 4 5 0 6 7 8 9 
// v2 : 1 2 3 4 5 0 6 7 8 9 

    v_t::iterator it2(v2.begin()); 
     for(v_t::iterator it(v1.begin()), end(v1.end()); it != end;) 
     *(it++) += *(it2++); 

    copy(v1.begin(), v1.end(), ostream_iterator<double>(cout, " ")); 
     cout << endl; 
    } 

程序的輸出是:

2 4 6 8 10 0 12 14 16 18 // This is correct and what I need 

,但如果我修改for循環是這樣的:

. 
. 
. 
v_t::iterator it2(v2.begin()); 
    for(v_t::iterator it(v1.begin()), end(v1.end()); it != end && (*(it++) += *(it2++));); 

copy(v1.begin(), v1.end(), ostream_iterator<double>(cout, " ")); 
     cout << endl; 
    } 

現在輸出的是:

2 4 6 8 10 0 6 7 8 9 

即每當遇到ters 0在它停止添加的兩個向量中的相同位置。爲什麼?超過0不會標記任何矢量的結束,是嗎?這也是一種價值。

如果您覺得它沒有意義,請隨時編輯我的問題的標題。

回答

3

那是因爲你正在檢查(*(it++) += *(it2++))作爲循環終止條件。所以當它碰到第六個元素時,它的值爲零,其結果爲it != end && (*(it++) += *(it2++));,並終止循環。

for(v_t::iterator it(v1.begin()), end(v1.end()); it != end && (*(it++) += *(it2++)););

應該是:

it != end && (*(it++) += *(it2++)) 

當他們都等於零,條件:

for(v_t::iterator it(v1.begin()), end(v1.end()); it != end; (*(it++) += *(it2++)));

1

您的for-loop的條件是it != end && *(it++) += *(it2++)。如果*it*it2都爲0,則*(it++) += *(it2++)將評估爲0,因此您的條件爲假,並且循環退出。

而不是把這個中的條件部分你的語句,你應該把它放在最後一部分,你留空:

for(v_t::iterator it(v1.begin()), end(v1.end()); it != end; *(it++) += *(it2++)) 
0

那是因爲你的循環的條件部分停止評估爲錯誤。

1

如果是後者,您的for循環的條件包括表達式*(it++) += *(it2++)

如果兩個迭代器都引用一個0,則該表達式的值爲0,這是false,從而導致循環終止。

爲什麼你在循環的條件下做附加作爲副作用?

2

這是因爲

(*(it++) += *(it2++)); 

結果爲零,當兩個*它和* IT2爲零。在C中零是錯誤的(所以它是在C++中)。

通過這種方式,嘗試分開遞增操作符和執行向量中的實際工作。它使代碼非常混亂,一起做這些棘手的事情(並且它不會讓你成爲更好的程序員;)

+0

+1 from myself :) – 2011-01-21 17:16:45