stl容器新增的实用方法

原位构造与容器的emplace系列函数

#include<iostream>
#include<list>

class Test
{
public:
	Test(int a, int b, int c)
	{
		ma = a;
		mb = b;
		mc = c;
		std::cout << "Test constructed." << std::endl;
	}
	~Test()
	{
		std::cout << "Test destructed." << std::endl;
	}
	Test(const Test& rhs)
	{
		if (this == &rhs)
		{
			return;
		}
		this->ma = rhs.ma;
		this->mb = rhs.mb;
		this->mc = rhs.mc;

		std::cout << "Test copy-constructed." << std::endl;
	}

private:
	int ma;
	int mb;
	int mc;
};

int main()
{
	std::list<Test> collections;
	//循环中的t对象在每次循环时,都分别调用了一次构造函数、拷贝构造函数和析构函数
	//以上总共循环10次,调用30次
	for (int i = 0; i < 10; i++)
	{
		Test t(1*i,2*i,3*i);
		collections.push_back(t);
	}

	//实际执行时只需调用Test类的构造函数10次,大大提高了执行效率
	std::list<Test> collections2;
	for (int i = 0; i < 10; i++)
	{
		collections2.emplace_back(1 * i, 2 * i, 3 * i);
	}
	return 0;
}

 

std::map的try_emplace方法与insert_or_assign方法

因为std::map中元素的key是唯一的,所以在实际开发中经常会有这样一类需求:向某个 map中插入元素时需要先检测 map中指定的 key是否存在,不存在时做插入操作,存在时直接取来使用;或者在指定的key不存在时做插入操作,存在时做更新操作。

在C++17中,map提供了一个try_emplace方法,该方法会检测指定的key是否存在,如果存在,则什么也不做。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值