[英]Why I can't see any ouput iterating this vector?
#include <iostream>
#include <string>
#include <vector>
#include <cstdio>
using std::printf;
int main()
{
std::vector<int> array{1, 2, 3, 4, 5};
for(auto i = array.begin(); i != array.end(); i++) {
auto index = i - array.begin();
if(array[index] == 2 || array[index] == 5) {
i = array.erase(i);
}
printf("iteration | %ld\n", index);
}
}
why I can't get any output from this? 为什么我不能从中得到任何输出? Using cout instead of printf works...
使用cout代替printf可以工作...
When you are erasing 5
, i = array.erase(i);
当您擦除
5
, i = array.erase(i);
will leave the iterator at end()
. 将迭代器保留在
end()
。 But then you do i++
which moves past the end, causing undefined behaviour. 但是,然后您执行
i++
,它就结束了,从而导致不确定的行为。
To fix this, change your logic so that i++
only occurs for iterations where i = array.erase(i);
要解决此问题,请更改逻辑,以使
i++
仅出现在其中i = array.erase(i);
迭代中i = array.erase(i);
did not occur. 没有发生。
Note: You could just write *i == 2 || *i == 5
注意:您可以只写
*i == 2 || *i == 5
*i == 2 || *i == 5
instead of having index
*i == 2 || *i == 5
而不是index
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.