vector压入对象使用注意事项:
- 无参构造器自实现
- reserve() 预留空间
- 如申请堆内存,自实现拷贝构造和移动构造
- 压入栈中的对象,不需要析构
API 使用:
class A
{
public:
A() {
cout<<"A():"<<this<<endl;
}
A(int i):_data(i)
{
cout<<"A(i):"<<this<<endl;
}
A(const A & other) {
cout<<"const A & other :"<<this<<"from"<<&other<<endl;
}
A & operator= (const A & other) {
cout<<"operator = :"<<this<<" from"<<&other<<endl;
}
~A() {
cout<<"~A() : "<<this<<endl;
}
private:
int _data;
}
1 resize: push_back和pop_back的结合使用
resize > size , push_back;
resize < size, pop_back
2 push_back:拷贝构造函数实现
int main()
{
vector<A> res;
A a;
res.push_back(a); // res = a ,拷贝构造
res.resize(0);
}
运行结果:
A():0x61feb0
const A & other : 0x6c7fd0 from 0x61feb0
~A(): 0x6c7fd0
~A(): 0x61feb0
3 insert: 插入元素,底层实现为移动构造和拷贝构造
int main()
{
vector<A> res;
res.reserve(10);
A a;
res.push_back(a);
res.insert(res.begin(),a);
}
运行结果:
A():0x62fea8
const A & other : 0x1c1118 from 0x62fea8
const A & other : 0x62fe54 from 0x62fea8
const A & other : 0x1c111c from 0x1c1118
operator= : 0x1c1118 from 0x62fe54
~A(): 0x62fe54
~A(): 0x62fea8
~A(): 0x1c1118
~A(): 0x1c111c
若压入的对象初始化,需自实现无参构造器,因为如果调用resize,会调用无参构造器A(), 若没有自实现,会报错
错误示例:
// A()
// {
// cout<<"A():"<<this<<endl;
// }
int main()
{
A a(10);
vector<A> res;
res.resize(0);
}
运行结果:
error: no matching constructor for initialization of ’ A’