我有一个程序只添加两个 vector 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
即每当它在两个 vector 中的同一位置遇到 0 时,它就会停止添加。为什么 ?大于 0 并不表示任何 vector 的结束,是吗?这也是一种值(value)。
如果您觉得我的问题标题没有意义,请随时修改它。
最佳答案
那是因为您正在检查 ( *(it++) += *(it2++) )
作为循环终止条件。因此,当它遇到第 6 个元素零时,它的计算结果为零,这使条件 it != end && ( *(it++) += *(it2++) );
失败并终止循环。
for(v_t::iterator it(v1.begin()), end(v1.end()); it != end && ( *(it++) += *(it2++) ); );
应该是:
for(v_t::iterator it(v1.begin()), end(v1.end()); it != end; ( *(it++) += *(it2++) ) );
关于c++ - Vector 的奇怪行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4761585/