【发布时间】:2020-02-16 13:29:25
【问题描述】:
我在使用带有向量 STL 的迭代器时遇到了这个错误。
代码:-
#include <iostream>
#include <vector>
void print_vec(std::vector<int> vec)
{
auto itr = vec.begin();
while (itr != vec.end())
std::cout << *itr++ << " ";
std::cout << std::endl;
}
int main(int argc, char* argv[])
{
std::vector<int> vals = { 1, 2, 3, 4, 5, 6 };
print_vec(vals);
auto it = vals.begin();
vals.insert(it, 100);
print_vec(vals);
it += 4;
std::cout << *it << "\n";
vals.insert(it, 200);
print_vec(vals);
return 0;
}
输出:-
1 2 3 4 5 6
100 1 2 3 4 5 6
5
0 100 1 2 3 4 5 6
double free or corruption (out)
Aborted (core dumped)
我不明白为什么会这样:修改向量后迭代器有问题吗?我认为我对迭代器的直觉是有缺陷的。
【问题讨论】:
-
std::vector<int>::iterator itr=vec.begin();-->auto itr = vector.begin();,拜托。为了可读性。 -
代码正在与迭代器失效赌博。