我有一个程序,只是像这样添加两个向量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不会标记任何矢量的结束,是吗?这也是一种价值。
如果您觉得它没有意义,请随时编辑我的问题的标题。
+1 from myself :) – 2011-01-21 17:16:45