std::pair讲解

在读vins-mono的代码里,在estimate_node.cpp里看到了std::pair,之前没怎么用过,于是做个笔记。

先看一下api

看一下,很简单,就是把两个类型任意对象配对。

在vins-mono的estimator.cpp里,用它来实现的功能是实现imu msg和pclmsg的配对。并放在vector里存储。

值得关注的是,在这种情况下,往vector里存储时,使用emplace_back而不是push back可以简化操作。

为什么这么说?

写了一个函数测试一下,使用vector时,只能存放左值,比如下图这么用,就会报错。我们不能用push_back,在push的同时构造对象。而用emplace_back就可以

我总结了一下push back 和emplace_back存放物体的过程区别

push_back() 

a) A constructor is called to create the temporary object 

b) A copy of the temporary object is created in the vector 

c) After copying the object the destructor is called to destory the temporary object 

Emplace_back: the object is created directly in the vector 。

用下面代码可以看出。请观察destructor触发的时机

class A{
int i;
public:
 A(int ii):i(ii) { cout<<"\nA constructor called!!"; }
 ~A() { cout<<"\nA destructor called!!"; }
 };

class B{
int i;
int j;
public:
B(int ii, int jj):i(ii),j(jj){cout<<"B constructor called";}
~B(){ cout<<"\nB destructor called!!";} 
};
void test1()
{
std::vector<A> v;

v.emplace_back(78);
cin.get();
}

void test2()
{
	std::vector<B> v;
v.emplace_back(12,12);
cin.get();
}
int main()
{
	test2();
 
 
return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值