【发布时间】:2019-12-23 16:40:52
【问题描述】:
当first1.erase(std::next(first1.begin(), i)); 被移除时,第二个循环被创建,这有点奇怪,因为first2.erase(first2.begin() + 4, first2.end()); 工作正常
#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;
}
输出:
Size of first1: 5
Size of second: 1
Size of first2: 4
Size of third: 2
我希望first1/second 与first2/third 相同
你可以在这里测试http://cpp.sh/9ltkw
【问题讨论】:
-
没有第二个循环,否则
first1的大小为4,second的大小为2 -
在迭代容器时修改容器是个坏主意。我建议拆分操作。复制然后擦除。
-
您的问题标题与您报告的内容不符。您的程序不会“崩溃”。
-
在可能的情况下进行迭代时,我忘了远离修改容器......我一直没有睡好,所以我的头脑有点不稳定
-
我的困惑是因为代码到达了
std::cout语句并产生了输出,而不是你所期望的。通常,“崩溃”意味着程序停止或异常终止,可能显示错误或异常。
标签: c++ loops for-loop vector erase