原位构造与容器的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是否存在,如果存在,则什么也不做。