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

  • 8
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
std::map.emplace是一个用于向std::map容器中插入元素的函数。它的作用是在map中插入一个键值对,并返回一个指向插入的元素的迭代器。emplace函数的参数可以是一个或多个键和值,它会使用这些参数直接构造一个新的键值对并插入到map中。如果插入成功,emplace函数会返回一个指向插入元素的迭代器,否则返回一个指向已存在的相同键的元素的迭代器。这种方式比使用insert函数更高效,因为emplace函数会避免额外的拷贝构造。 例如,可以使用emplace函数向一个std::map<std::string, std::string>对象中插入元素: std::map<std::string, std::string> m; m.emplace(std::make_pair("key", "value")); 这样就向map中插入了一个键值对,键为"key",值为"value"。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [【C++】17. map []操作符、insert()、emplace()](https://blog.csdn.net/u011754972/article/details/116798048)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [std::map emplace示例](https://blog.csdn.net/qq_34999565/article/details/119908509)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值