[英]Why does vector::erase seem to cause a crash?
When first1.erase(std::next(first1.begin(), i));
当
first1.erase(std::next(first1.begin(), i));
is removed the second loop is made, its a bit strange since first2.erase(first2.begin() + 4, first2.end());
删除了第二个循环,它有点奇怪,因为
first2.erase(first2.begin() + 4, first2.end());
works okay工作正常
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> first1 = {0,1,2,3,4,5};
std::vector<int> first2 = {0,1,2,3,4,5};
std::vector<int> second;
std::vector<int> third;
for(size_t i = 4; i < first1.size(); ++i){
auto child = first1[i];
second.push_back(child);
first1.erase(std::next(first1.begin(), i));
}
third.assign(first2.begin() + 4, first2.end());
first2.erase(first2.begin() + 4, first2.end());
std::cout << "Size of first: " << int (first1.size()) << '\n';
std::cout << "Size of second: " << int (second.size()) << '\n';
std::cout << "Size of first: " << int (first2.size()) << '\n';
std::cout << "Size of third: " << int (third.size()) << '\n';
return 0;
}
Output:输出:
Size of first1: 5
Size of second: 1
Size of first2: 4
Size of third: 2
I expected first1/second
to be the same as first2/third
我希望
first1/second
与first2/third
相同
you can test it here http://cpp.sh/9ltkw你可以在这里测试它http://cpp.sh/9ltkw
After the first iteration of the loop在循环的第一次迭代之后
for(size_t i = 4; i < first1.size(); ++i){
auto child = first1[i];
second.push_back(child);
first1.erase(std::next(first1.begin(), i));
}
i
will be equal to 5
and first1.size() also will be equal to 5. So only one element of the vector is erased. i
将等于5
而 first1.size() 也将等于 5。因此,仅擦除向量的一个元素。
You could rewrite the loop like你可以像这样重写循环
for(size_t i = 4; i != first1.size(); ){
auto child = first1[i];
second.push_back(child);
first1.erase(std::next(first1.begin(), i));
}
to get the expected result.以获得预期的结果。
In these statements在这些声明中
third.assign(first2.begin() + 4, first2.end());
first2.erase(first2.begin() + 4, first2.end());
there are assigned and erased 2 elements.有分配和擦除 2 个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.