map添加元素的过程(都需要哪些操作?)
- C/C++ code
#include<iostream>#include<map>using namespace std;class Car{public: Car(int no=0){m_no=no;cout<<"creat,no is "<<no<<endl;}; Car(const Car& other){m_no=other.m_no;cout<<"copy, NO. is "<<other.m_no<<endl;}; ~Car(){;}; friend ostream& operator << (ostream& os,const Car &c); Car& operator = (const Car& other){m_no=other.m_no;cout<<"set, NO. is "<<other.m_no<<endl;}private: int m_no;};ostream& operator << (ostream& os,const Car &c){ os<<"The NO. of the Car is "<<c.m_no; return os;}int main(){ map<int,Car> map_i; Car a(1),b(2),c(3); cout<<"start"<<endl; map_i[1]=a; //创建空对象,拷贝两次后赋值 map_i.insert(pair<int,Car>(2,b)); //拷贝b三次 map_i.insert(make_pair(3,c)); //拷贝c四次 cout<<"set"<<endl; map<int,Car>::iterator it; for(it=map_i.begin();it!=map_i.end();it++){ cout<<it->first<<" "<<it->second<<endl; }}输出:
creat,no is 1
creat,no is 2
creat,no is 3
start
creat,no is 0
copy, NO. is 0
copy, NO. is 0
set, NO. is 1
copy, NO. is 2
copy, NO. is 2
copy, NO. is 2
copy, NO. is 3
copy, NO. is 3
copy, NO. is 3
copy, NO. is 3
set
1 The NO. of the car is 1
2 The NO. of the car is 2
3 The NO. of the car is 3
每次往map里增加对象那么多拷贝,要是大对象不是很浪费时间?
为什么会有这么多拷贝呢?希望高手指点
[解决办法]