上一篇博客说道vector中放入struct。我们先构造一个struct对象。再push_back。

那段代码中,之所以不能使用emplace_back,就是由于我们定义的struct没有显示的构造函数。

emplace和解?

放列的意思。

这次我们不把struct当做vector的元素了。我们把一个class当做vector的元素,写下代码:

#include <iostream>
#include <vector>
#include<string>
using namespace std;
class CText {
private:
string str;
public:
text(string s) :str(s) {
}
void show()const {
cout << str << endl;
} };
int main()
{
vector<CText > vi;
vi.emplace_back("hey");
vi.front().show();
vi.push_back("girl");//错误
vi.back().show();
return 0;
}

当中vi.push_back(“girl”);这条语句错误。VS2015报错为:

error C2664: “void std::vector<text,std::allocator<_Ty>>::push_back(const text &)”: 无法将參数 1 从“const char [5]”转换为“text &&”

但此时我们稍作改动:

把 vi.push_back(“girl”) 改为

vi.push_back(CText(“girl”));

问题就攻克了。。

简而言之,就是empace_back与push_back相比。替我们省去了调用CText进行构造。

emplace_back

加入一个新元素到结束的容器。该元件是构成在就地,即没有复制或移动操作进行。

inserts a new element at the end of the vector, right after its current last element. This new element is constructed in place using args as the arguments for its constructor.

This effectively increases the container size by one, which causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.

The element is constructed in-place by calling allocator_traits::construct with args forwarded.

A similar member function exists, push_back, which either copies or moves an existing object into the container.

写到这里。你应该明确emplace_back怎样是也了吧。

最后再来一段代码。涉及到使用右值引用和std::move的:

#include <vector>
#include <string>
#include <iostream> 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 main()
{
std::vector<President> elections;
std::cout << "emplace_back:\n";
elections.emplace_back("Nelson Mandela", "South Africa", 1994); std::vector<President> reElections;
std::cout << "\npush_back:\n";
reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936)); 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";
}
} //输出:
emplace_back:
I am being constructed. push_back:
I am being constructed.
I am being moved. Contents:
Nelson Mandela was elected president of South Africa in 1994.
Franklin Delano Roosevelt was re-elected president of the USA in 1936.

实战c++中的vector系列--知道emplace_back为何优于push_back吗?的更多相关文章

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

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

  2. 实战c++中的vector系列--creating vector of local structure、vector of structs initialization

    之前一直没有使用过vector<struct>,如今就写一个简短的代码: #include <vector> #include <iostream> int mai ...

  3. 实战c++中的vector系列--再谈vector的insert()方法(都是make_move_iterator惹的祸)

    之前说过了关于vector的insert()方法,把vector B的元素插入到vector A中.vector A中的结果我们可想而知,可是vector B中的元素还会怎样? 看看之前写过的程序: ...

  4. 实战c++中的vector系列--copy set to vector(别混淆了reserve和resize)

    stl算法中有个copy函数.我们能够轻松的写出这种代码: #include <iostream> #include <algorithm> #include <vect ...

  5. 实战c++中的vector系列--vector应用之STL的find、find_if、find_end、find_first_of、find_if_not(C++11)

    使用vector容器,即避免不了进行查找,所以今天就罗列一些stl的find算法应用于vector中. find() Returns an iterator to the first element ...

  6. 实战c++中的vector系列--将迭代器转换为索引

    stl的迭代器非常方便 用于各种算法. 可是一想到vector.我们总是把他当做数组,总喜欢使用下标索引,而不是迭代器. 这里有个问题就是怎样把迭代器转换为索引: #include <vecto ...

  7. 实战c++中的vector系列--构造、operator=和assign差别

    vector或许是实际过程中使用最多的stl容器.看似简单,事实上有非常多技巧和陷阱. 着重看一看vector的构造,临时依照C++11: default (1) explicit vector (c ...

  8. 实战c++中的vector系列--正确释放vector的内存(clear(), swap(), shrink_to_fit())

    关于vector已经写的差不多了,似乎要接近尾声了,从初始化到如何添加元素再到copy元素都有所涉及,是时候谈一谈内存的释放了. 是的,对于数据量很小的vector,完全没必要自己进行主动的释放,因为 ...

  9. 实战c++中的vector系列--vector&lt;unique_ptr&lt;&gt;&gt;初始化(全部权转移)

    C++11为我们提供了智能指针,给我们带来了非常多便利的地方. 那么假设把unique_ptr作为vector容器的元素呢? 形式如出一辙:vector<unique_ptr<int> ...

随机推荐

  1. 换掉Tomcat默认图标

    将<Tomcat_home>下的/webapps/ROOT的favicon.ico替换成你自己的图标,名还得是这个名. 然后清除浏览器缓冲,webapp默认的小猫图标就被换掉了. 效果如下 ...

  2. 循环栅栏:CyclicBarrier(司令要求任务) 读书笔记

    可以理解为循环栅栏,栅栏就是一种障碍物.假如我们将计数器设置为10,那么凑齐第一批10个线程后,计数器就会归零,然后接着凑齐下一批10个线程,这就是循环栅栏的含义. 构造器: public Cycli ...

  3. setsockopt之 TCP_KEEPIDLE/TCP_KEEPINTVL/TCP_KEEPCNT

    setsockopt之 TCP_KEEPIDLE/TCP_KEEPINTVL/TCP_KEEPCNT /*检测网线非法断开*/    setsockopt(iSockFd, SOL_SOCKET, S ...

  4. VMware 9.0.1安装Mac OS X Mountain Lion 10.8.2

    原地址:http://zengwu3915.blog.163.com/blog/static/278348972013117114742496/ 所需软件1.VMware Workstation Bu ...

  5. ant design pro(二)布局

    一.概述 参看地址:https://pro.ant.design/docs/layout-cn 其实在上述地址ant-design上已经有详细介绍,本文知识简述概要. 页面整体布局是一个产品最外层的框 ...

  6. 【android开发】使用PopupWindow实现页面点击顶部弹出下拉菜单

    没有太多花样,也没有很复杂的技术,就是简单的PopupWindow的使用,可以实现点击弹出一个自定义的view,view里可以随便设计,常用的可以放一个listview. demo中我只是一个点击展示 ...

  7. 迭代器适配器{(插入迭代器back_insert_iterator)、IO流迭代器(istream_iterator、ostream_iterator)}

    一.迭代器适配器 反向迭代器 插入迭代器 IO流迭代器 其中反向迭代器可以参考以前的文章. 二.插入迭代器 插入迭代器实际上是一个输出迭代器(*it=; ++) back_insert_iterato ...

  8. Provisional headers are shown(一)

    谷歌浏览器调试的时候,这个警告经常出现.但是每次产生的原因可能都是不一样的. 这篇文档记录我遇到的其中一次. 现象:一个并发的错误信息: CAUTION:request is not finished ...

  9. 最短作业优先(SJF)

    1. 最短作业优先: 最短作业优先(SJF)是一种调度任务请求的调度策略.每个任务请求包含有请求时间(即向系统提交的请求的时间)和持续时间(即完成任务所需时间). 当前任务完成后,SJF策略会选择最短 ...

  10. tp模型和数据库操作方法

    一.新建的模型名和表名一样,采用驼峰式,如表名user_type模型取名为UserType namespace app\index\model;use think\Model;class UserTy ...