vector压入对象技巧和api使用

文章讲述了在C++中使用vector时,特别是在压入元素、resize操作和insert方法时,涉及的构造函数(包括无参构造、拷贝构造和移动构造)的重要性,以及自实现无参构造器以避免编译错误的必要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vector压入对象使用注意事项:

  1. 无参构造器自实现
  2. reserve() 预留空间
  3. 如申请堆内存,自实现拷贝构造和移动构造
  4. 压入栈中的对象,不需要析构

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’

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

八月的雨季997

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值