emplace()

大部分的容器在 C++11 中对于添加元素除了常见的 insert 或者 pusb_back/push_front 之外还提供一个新的方法叫做 emplace。 比如你想要向 std::vector 的末尾添加一个元素,示例代码如下:

/// @note 传统方式
std::vector<int> nums;
nums.push_back(1);

/// @note C++11
std::vector<int> nums;
nums.emplace_back(1);

emplace() 是 C++ 11 标准新增加的成员函数,用于在 vector 容器指定位置之前插入一个新的元素。

再次强调,emplace() 每次只能插入一个元素,而不是多个。

该函数的语法格式如下:

iterator emplace (const_iterator pos, args...);

其中,pos 为指定插入位置的迭代器;args… 表示与新插入元素的构造函数相对应的多个参数;该函数会返回表示新插入元素位置的迭代器。

简单的理解 args…,即被插入元素的构造函数需要多少个参数,那么在 emplace() 的第一个参数的后面,就需要传入相应数量的参数。

举个例子:

#include <vector>
#include <iostream>
using namespace std;

int main()
{
    std::vector<int> demo1{1,2};
    //emplace() 每次只能插入一个 int 类型元素
    demo1.emplace(demo1.begin(), 3);
    for (int i = 0; i < demo1.size(); i++) {
        cout << demo1[i] << " ";
    }
    return 0;
}

运行结果为:

3 1 2

使用 emplace 的优点是避免产生不必要的临时变量,避免不必要的临时对象的产生,举个例子:

struct Foo {
    Foo(int n, double x);
};

std::vector<Foo> v;
v.emplace(someIterator, 42, 3.1416);     ///< 没有临时变量产生
v.insert(someIterator, Foo(42, 3.1416)); ///< 需要产生一个临时变量
v.insert(someIterator, {42, 3.1416});    ///< 需要产生一个临时变量

从以上的例子中,我们可以看出 emplace 相较于 insert,emplace 的语法看起来比较特别,后面两个参数自动用来构造 vector 内部的 Foo 对象。这是因为其内部利用了 C++11 的两个新特性 —— 变参模板 和 完美转发。

[变参模板] 使得 emplace 可以接受任意参数,这样就可以适用于任意对象的构建。
[完美转发] 使得接收下来的参数能够原样完美地传递给对象的构造函数,这带来另一个方便性就是即使是构造函数声明为 explicit 它还是可以正常工作,因为它不存在临时变量和隐式转换。

struct Bar
{
    Bar(int a) {}
    explicit Bar(int a, double b) {} ///< 必须显示调用
};

int main(void)
{
    vector<Bar> bv;
    bv.push_back(1);      ///< 隐式转换生成临时变量
    bv.push_back(Bar(1)); ///< 显示构造临时变量
    bv.emplace_back(1);   ///< 没有临时变量

    //bv.push_back({1, 2.0}); ///< 无法进行隐式转换
    bv.push_back(Bar(1, 2.0));///< 显示构造临时变量
    bv.emplace_back(1, 2.0);  ///< 没有临时变量

    return 0;
}

再来看一个例子,通过下面这段程序,就可以直观看出两者运行效率的差异:

#include <vector>
#include <iostream>
using namespace std;
class testDemo
{
public:
    testDemo(int num) :num(num) {
        std::cout << "调用构造函数" << endl;
    }
    testDemo(const testDemo& other) :num(other.num) {
        std::cout << "调用拷贝构造函数" << endl;
    }
    testDemo(testDemo&& other) :num(other.num) {
        std::cout << "调用移动构造函数" << endl;
    }

    testDemo& operator=(const testDemo& other);
private:
    int num;
};
testDemo& testDemo::operator=(const testDemo& other) {
    this->num = other.num;
    return *this;
}
int main()
{
    cout << "insert:" << endl;
    std::vector<testDemo> demo2{};
    demo2.insert(demo2.begin(), testDemo(1));

    cout << "emplace:" << endl;
    std::vector<testDemo> demo1{};
    demo1.emplace(demo1.begin(), 1);
    return 0;
}

运行结果为:

insert:
调用构造函数
调用移动构造函数
emplace:
调用构造函数

注意,当拷贝构造函数和移动构造函数同时存在时,insert() 会优先调用移动构造函数。

可以看到,通过 insert() 函数向 vector 容器中插入 testDemo 类对象,需要调用类的构造函数和移动构造函数(或拷贝构造函数);而通过 emplace() 函数实现同样的功能,只需要调用构造函数即可。

简单的理解,就是 emplace() 在插入元素时,是在容器的指定位置直接构造元素,而不是先单独生成,再将其复制(或移动)到容器中。因此,在实际使用中,推荐大家优先使用 emplace()。

值得注意的是 map 类型的 emplace 处理比较特殊,因为和其他的容器不同,map 的 emplace 方法把它接收到的所有的参数都一起转发给 pair 的构造函数。但是对于一个 pair 来说,它既需要构造它的 key 又需要构造它的 value。如果我们按照之前普通的语法使用变参模板的话,则它是无法区分哪些参数用来构造 key, 哪些用来构造 value的。 比如下面的代码

// @note 无法区分哪个参数用来构造 key 哪些用来构造 value
// 有可能是 string s("hello", 1), complex<double> cpx(2) 
// 也有可能是 string s("hello"), complex<double> cpx(1, 2)
map<string, complex<double>> scp;
scp.emplace("hello", 1, 2); 
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

yitahutu79

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

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

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

打赏作者

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

抵扣说明:

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

余额充值