std::map emplace示例

emplace 

emplace操作是从C++11开始引入新特性,emplace操作是直接通过参数构造元素而不是拷贝元素到容器中这样可以减少拷贝从而提高性能。对于map是没有emplace_front、emplace_after、emplace_back这些操作的。

std::map<Key,T,Compare,Allocator>::emplace

template< class... Args >
std::pair<iterator,bool> emplace( Args&&... args );

(since C++11)

Inserts a new element into the container constructed in-place with the given args if there is no element with the key in the container.

注意返回值也是一个std::pair

#include <iostream>
#include <utility>
#include <string>
#include <map>
 
int main()
{
    std::map<std::string, std::string> m;
 
    // uses pair's move constructor
    //使用移动构造
    m.emplace(std::make_pair(std::string("a"), std::string("a")));
 
    // uses pair's converting move constructor
    //使用隐式转换移动构造函数,和上一个区别是这里的“a”会隐式转换成std::string
    m.emplace(std::make_pair("b", "abcd"));
 
    // uses pair's template constructor
    //使用模板构造
    m.emplace("d", "ddd");
 
    // uses pair's piecewise constructor
    m.emplace(std::piecewise_construct,
              std::forward_as_tuple("c"),
              std::forward_as_tuple(10, 'c'));
    // as of C++17, m.try_emplace("c", 10, 'c'); can be used
 
    for (const auto &p : m) {
        std::cout << p.first << " => " << p.second << '\n';
    }
}

输出:

a => a
b => abcd
c => cccccccccc
d => ddd

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值