当前位置:网站首页>Implementation principle of function emplace_back in vector
Implementation principle of function emplace_back in vector
2022-08-04 11:24:00 【Old stubborn and cute】
vector中函数emplace_back的实现原理
在vector中的emplace_back函数, 其效率比push_back高很多!
/*例子中使用的Student类的声明*/
class Student
{
private:
int age;
public:
Student();
explicit Student(int age);
~Student();
int getAge();
};
原理分析
push_back函数
vector<Student> team;
team.push(Student(24));
代码运行过程中, 首先是执行Student()创建了一个临时的Student对象, Then use the copy constructor to copy the value of the member variable of this temporary object toteamin the space.
There are two reasons for the slow efficiency:
- 创建临时Student对象时,需要申请内存空间,Allocating memory space has always been a time-consuming operation
- The copy operation of the copy constructor is also requiredCPU时间的
emplace_back函数
vector<Student> team;
team.emplace_back(24);
- This code achieves the same result as above,都在team里添加了一个24岁的Student对象.
- 但在执行效率上,emplace_back函数很快
其原理就是emplace_backThe function is directly inteamon the existing space,调用了Student类的构造函数,Saves the memory space application for temporary objects and the copy operation of the copy constructor.
emplace_back实现原理
void* ptr = malloc(sizeof(Student));
new (ptr)Student(100);
cout << ((Student*)ptr)->getAge() << endl;
第1行:主要是分配一个Student对象所需的内存空间,但在vector里,这步不需要考虑,内部会在实现;
第2行:这才是重点,通过这样的语法,就可以对已在的内存空间,调用相应的Student类构造函数进行初始化;
第3行:输出验证结果.
边栏推荐
- POJ2367Genealogical tree题解
- 深度学习------pytorch实现cifar10数据集
- Leetcode - using sequence traversal features first completed 114. The binary tree to the list
- DQL-查询操作
- 『快速入门electron』之实现窗口拖拽
- 命令模式(Command)
- 化繁为简!阿里新产亿级流量系统设计核心原理高级笔记(终极版)
- 【机器学习】:如何对你的数据进行分类?
- Mysql——》类型转换符binary
- 【目标检测】YOLOv4特征提取网络——CSPDarkNet53结构解析及PyTorch实现
猜你喜欢

Oracle中对临时表空间执行shrink操作

Leetcode刷题——构造二叉树(105. 从前序与中序遍历序列构造二叉树、106. 从中序与后序遍历序列构造二叉树)

Leetcode——利用先序遍历特性完成114. 二叉树展开为链表

audio_policy_configuration.xml配置文件详解

表的完整性约束;非外键约束

Zikko上市同时搭载HDMI2.1和2.5GbE新款雷电4扩展坞

ESP8266-Arduino编程实例-MQ3酒精传感器驱动

Leetcode brush questions - binary search tree related topics (98. Verify binary search tree, 235. The nearest common ancestor of binary search tree, 1038. From binary search tree to bigger sum tree, 5

中介者模式(Mediator)

The use of DDR3 (Naive) in Xilinx VIVADO (3) simulation test
随机推荐
【LeetCode】232.用栈实现队列
CVPR 2022 | 从人体网格预测骨架,是真正的生理学骨架!
MTBF是什么意思?交换机做MTBF有什么要求?MTTF、MTBF和MTTR的区别是什么?
Leetcode刷题——路径总和
知道创宇EDR系统实力通过中国信通院端点检测与响应产品能力评测
请 AI 画家弄了个 logo,网友热议:画得非常好,下次别画了!
小程序实战(三) - head组件的封装与使用
apache dolphin scheduler 文件dolphinscheduler-daemon.sh详解
Xilinx VIVADO 中 DDR3(Naive)的使用(1)创建 IP 核
*iframe*
Move the blog to CSDN
网管交换机与非网管交换机如何选择?
手搓一个“七夕限定”,用3D Engine 5分钟实现烟花绽放效果
北京大学,新迎3位副校长!其中一人为中科院院士!
Win11文件类型怎么改?Win11修改文件后缀的方法
Win11 file types, how to change?Win11 modify the file suffix
网管型交换机比傻瓜交换机多了哪些功能
DQL-查询操作
Leetcode刷题——543. 二叉树的直径、617. 合并二叉树(递归解决)
yolov5——detect.py代码【注释、详解、使用教程】