C++11中,针对顺序容器(如vector、deque、list),新标准引入了三个新成员:emplace_front、emplace和emplace_back,这些操作构造而不是拷贝元素。这些操作分别对应push_front、insert和push_back,允许我们将元素放置在容器头部、一个指定位置之前或容器尾部。

当调用push或insert成员函数时,我们将元素类型的对象传递给它们,这些对象被拷贝到容器中。而当我们调用一个emplace成员函数时,则是将参数传递给元素类型的构造函数。emplace成员使用这些参数在容器管理的内存空间中直接构造元素。

emplace函数的参数根据元素类型而变化,参数必须与元素类型的构造函数相匹配。emplace函数在容器中直接构造元素。传递给emplace函数的参数必须与元素类型的构造函数相匹配。

其它容器中,std::forward_list中的emplace_after、emplace_front函数,std::map/std::multimap中的emplace、emplace_hint函数,std::set/std::multiset中的emplace、emplace_hint,std::stack中的emplace函数,等emplace相似函数操作也均是构造而不是拷贝元素。

emplace相关函数可以减少内存拷贝和移动。当插入rvalue,它节约了一次move构造,当插入lvalue,它节约了一次copy构造。

下面是从其他文章中copy的测试代码,详细内容介绍可以参考对应的reference:

#include "emplace.hpp"
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <tuple>
#include <utility> namespace emplace_ { /////////////////////////////////////////////////////////
// reference: http://www.cplusplus.com/reference/vector/vector/emplace_back/
int test_emplace_1()
{
{
/*
template <class... Args>
void emplace_back (Args&&... args);
*/
std::vector<int> myvector = { , , }; myvector.emplace_back();
myvector.emplace_back(); std::cout << "myvector contains:";
for (auto& x : myvector)
std::cout << ' ' << x;
std::cout << '\n';
} {
/*
template <class... Args>
iterator emplace (const_iterator position, Args&&... args);
*/
std::vector<int> myvector = { , , }; auto it = myvector.emplace(myvector.begin() + , );
myvector.emplace(it, );
myvector.emplace(myvector.end(), ); std::cout << "myvector contains:";
for (auto& x : myvector)
std::cout << ' ' << x;
std::cout << '\n';
} return ;
} ///////////////////////////////////////////////////////
// reference: http://en.cppreference.com/w/cpp/container/vector/emplace_back
namespace {
struct President {
std::string name;
std::string country;
int year; President(std::string p_name, std::string p_country, int p_year)
: name(std::move(p_name)), country(std::move(p_country)), year(p_year)
{
std::cout << "I am being constructed.\n";
}
President(President&& other)
: name(std::move(other.name)), country(std::move(other.country)), year(other.year)
{
std::cout << "I am being moved.\n";
}
President& operator=(const President& other) = default;
};
} int test_emplace_2()
{
/*
The following code uses emplace_back to append an object of type President to a std::vector.
It demonstrates how emplace_back forwards parameters to the President constructor and shows
how using emplace_back avoids the extra copy or move operation required when using push_back.
*/
std::vector<President> elections;
std::cout << "emplace_back:\n";
elections.emplace_back("Nelson Mandela", "South Africa", ); std::vector<President> reElections;
std::cout << "\npush_back:\n";
reElections.push_back(President("Franklin Delano Roosevelt", "the USA", )); std::cout << "\nContents:\n";
for (President const& president : elections) {
std::cout << president.name << " was elected president of "
<< president.country << " in " << president.year << ".\n";
}
for (President const& president : reElections) {
std::cout << president.name << " was re-elected president of "
<< president.country << " in " << president.year << ".\n";
} return ;
} ////////////////////////////////////////////////////////////////
// reference: https://stackoverflow.com/questions/4303513/push-back-vs-emplace-back
int test_emplace_3()
{
/*
template <class... Args>
pair<iterator,bool> emplace (Args&&... args);
*/
typedef std::tuple<int, double, std::string> Complicated; std::map<int, Complicated> m;
int anInt = ;
double aDouble = 5.0;
std::string aString = "C++"; // cross your finger so that the optimizer is really good
//m.insert(/*std::make_pair*/std::pair<int, Complicated>(4, Complicated(anInt, aDouble, aString)));
m.insert(std::make_pair(, Complicated(anInt, aDouble, aString))); // should be easier for the optimizer
m.emplace(, Complicated(anInt, aDouble, aString));
/*
std::piecewise_construct: This constant value is passed as the first argument to construct a pair object
to select the constructor form that constructs its members in place by forwarding the elements of two
tuple objects to their respective constructor.
*/
m.emplace(std::piecewise_construct, std::make_tuple(), std::make_tuple(anInt, aDouble, aString)); return ;
} //////////////////////////////////////////////////////////////
// reference: https://corecplusplustutorial.com/difference-between-emplace_back-and-push_back-function/
namespace {
class Dat {
int i;
std::string ss;
char c; public:
Dat(int ii, std::string s, char cc) :i(ii), ss(s), c(cc) { } ~Dat() { }
};
} int test_emplace_4()
{
std::vector<Dat> vec;
vec.reserve(); vec.push_back(Dat(, "New", 'G')); // efficiency lesser
//vec.push_back(678, "Newer", 'O'); // error,push_back can’t accept three arguments
vec.emplace_back(, "Newest", 'D'); // work fine, efficiency is also more return ;
} } // namespace emplace_

C++11 vector使用emplace_back代替push_back的更多相关文章

  1. 编程杂谈——使用emplace_back取代push_back

    近日在YouTube视频上看到关于vector中emplace_back与push_back区别的介绍,深感自己在现代C++中还是有不少遗漏的知识点,遂写了段代码,尝试比较两者的差别. 示例代码 #i ...

  2. C++11使用emplace_back代替push_back

    最近在写一段代码的时候,突然很好奇C++11中对push_back有没有什么改进以增加效率,上网搜了一些资料,发现果然新增了emplace_back方法,比push_back的效率要高很多. 首先,写 ...

  3. 学习 emplace_back() 和 push_back 的区别 emplace_back效率高

    在引入右值引用,转移构造函数,转移复制运算符之前,通常使用push_back()向容器中加入一个右值元素(临时对象)的时候,首先会调用构造函数构造这个临时对象,然后需要调用拷贝构造函数将这个临时对象放 ...

  4. 实战c++中的vector系列--emplace_back造成的引用失效

    上篇将了对于struct或是class为何emplace_back要优越于push_back,可是另一些细节没有提及.今天就谈一谈emplace_back造成的引用失效. 直接撸代码了: #inclu ...

  5. vector 类中的 push_back( ) 函数

    函数名 push_back,算法语言里面的一个函数名,如:   1) c++中的vector头文件里面就有这个push_back函数:   2) 在vector类中作用为在vector尾部加入一个数据 ...

  6. (转)C++11使用emplace_back代替push_back (其中有关于右值引用)

    最近在写一段代码的时候,突然很好奇C++11中对push_back有没有什么改进以增加效率,上网搜了一些资料,发现果然新增了emplace_back方法,比push_back的效率要高很多. 首先,写 ...

  7. C++ std::vector emplace_back 优于 push_back 的理由

    #include <iostream> #include <vector> #include <chrono> #include <windows.h> ...

  8. emplace_back与push_back的区别

    std::vector::emplace_back     C++   Containers library   std::vector   template< class... Args &g ...

  9. 【C/C++开发】emplace_back() 和 push_back 的区别

    在引入右值引用,转移构造函数,转移复制运算符之前,通常使用push_back()向容器中加入一个右值元素(临时对象)的时候,首先会调用构造函数构造这个临时对象,然后需要调用拷贝构造函数将这个临时对象放 ...

随机推荐

  1. python两个 list 获取交集,并集,差集的方法

    1. 获取两个list 的交集 #方法一: a=[2,3,4,5] b=[2,5,8] tmp = [val for val in a if val in b] print tmp #[2, 5] # ...

  2. 【C++】C++中的引用与指针

    想必大家对C++中的指针都有所了解,但是什么是引用呢?C++11标准引入了“引用”的新功能. 引用 引用(reference):给对象起了另外一个名字,引用类型引用(refers to)另外一种类型, ...

  3. system generator学习笔记【01】

    作者:桂. 时间:2018-05-18  18:26:50 链接:http://www.cnblogs.com/xingshansi/p/9045914.html 前言 学习使用system gene ...

  4. Docker的学习

    学习地址:http://blog.51cto.com/lizhenliang  和 他的视频 一  Docker 的介绍和安装 二 镜像管理 三 容器管理 四 管理应用程序数据 五 使用Docker知 ...

  5. 使用 fail2ban 防御 SSH 服务器的暴力破解攻击

    对于SSH服务的常见的攻击就是暴力破解攻击——远程攻击者通过不同的密码来无限次地进行登录尝试.当然SSH可以设置使用非密码验证验证方式来对抗这种攻击,例如公钥验证或者双重验证.将不同的验证方法的优劣处 ...

  6. vue 实站技巧总结

    多个页面都使用的到方法,放在 vue.prototype上会很方便 刚接触 vue的时候做过一件傻事,因为封装了一个异步请求接口post,放在 post.js文件里面,然后在每个需要使用异步请求的页面 ...

  7. SQL递归方式实现省市区县级别查询

    数据库脚本 CREATE TABLE [dbo].[Std_Area]( [Id] [int] NOT NULL, [Name] [nvarchar](50) NULL, [ParentId] [in ...

  8. 如何使用maven优雅地管理项目版本号

    原文: https://blog.csdn.net/TeleDCOS/article/details/79853782

  9. netty 的 JBoss Marshalling 编码解码

    一. JBoss Marshalling 简介. JBoss Marshalling 是一个Java 对象序列化包,对 JDK 默认的序列化框架进行了优化,但又保持跟 Java.io.Serializ ...

  10. 《effective Go》读后记录:GO基础

    一个在线的Go编译器 如果还没来得及安装Go环境,想体验一下Go语言,可以在Go在线编译器 上运行Go程序. 格式化 让所有人都遵循一样的编码风格是一种理想,现在Go语言通过gofmt程序,让机器来处 ...