daiquxing451800861
Daivesi
2016-09-02 14:14

在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条回答

为你推荐