在C++里面 insert()方法不能连续插入两个元素,这里我用的是迭代器

#include
#include

using namespace std;

class Element{
private:
string name;
string Makein;
double price;
public:
friend ostream &operator<<(ostream &out,Element &e);
Element(){
name = "unknown";
Makein = "unknown";
price = 0;
}
Element(const string n, const string m, int p):name(n),Makein(m),price(p){}

};

ostream &operator<<(ostream &out,Element &e)
{
out <<"乐器名字:" << e.name << ",乐器制造地:" << e.Makein << ",乐器价格" << e.price;
return out;
}

void showV(vector &v)
{
for(int i = 0; i < v.size(); i++)
{
cout << v.at(i) << endl;
}
}
int main()
{
Element e1("钢琴","德国",23000);
Element e2("小提琴","意大利",18000);
Element e3("吉他","美国",12000);
Element e4("曲笛","北京",2000);
Element e5("梆笛","江苏",1800);
Element e6("琵琶","江苏",2800);

vector<Element> v(6,e1);
vector<Element>::iterator it = v.begin();
cout << "sizeof(Element)" << sizeof(Element) << endl;
v.insert(++it,e2);
showV(v);

// it = v.begin();

v.insert(++it,e3);   //这里运行结果是内存访问出错
cout << *it << endl;

cout << endl;

showV(v);
cout << v.size() << endl;
return 0;

}

2个回答

迭代器经典大坑。执行insert或erase后原来的迭代器会失效掉,必须重新获取。

楼上说的对,在第一个insert后加断点看迭代器的值就可以发现问题

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问