vector学习之insert和emplace操作
程序员文章站
2022-02-05 19:28:23
...
我们知道向vector容器里插入数据时使用insert函数,但是C++11又增加了一个emplace函数,它的功能与emplace_back原理一样,是构造一个对象添加到容器中,这样就省去了拷贝的副本,提高了性能,操作对比如下:
#include <iostream>
#include <vector>
#include <time.h>
using namespace std;
typedef struct Personal
{
int m_age;
int m_height;
string m_name;
Personal(int age, int height, std::string name)
:m_age(age), m_height(height), m_name(name)
{
//cout << "constructed=======Personal===age=" << age << endl;
}
Personal(const Personal& other)
:m_age(other.m_age)
, m_height(other.m_height)
, m_name(other.m_name)
{
//cout << "copy constructed====Personal==age=" << m_age << endl;
}
~Personal()
{
//cout << "destructor~~~Personal=========age~" << m_age << endl;
}
}Person;
void insert_emplace_reserve_Test()
{
int count = 214748;//214748
string name = string("床前明月光,疑似地上霜,举头望明月,低头思故乡。");
double startTime1 = clock();//1计算开始
vector<Person> vec1;
cout << "insert_emplace_reserve_Test==========" <<endl;
for(int i = 0; i < count; i++)//214748
{
Person person(i, i, name);
vec1.insert(vec1.begin() + i, person);
}
double endTime1 = clock();//1时间结束
cout << "vec1.size=" << vec1.size() << " vec1.capacity=" << vec1.capacity() << endl;
vec1.clear();
cout << "for 1 run time is: " << (double)(endTime1 - startTime1) / CLOCKS_PER_SEC << "s" << endl;
cout << endl;
double startTime2 = clock();//2计算开始
for(int i = 0; i < count; i++)
{
Person person(i, i, name);
vec1.emplace(vec1.begin() + i, person);
}
double endTime2 = clock();//2时间结束
cout << "vec2.size=" << vec1.size() << " vec2.capacity=" << vec1.capacity() << endl;
vec1.clear();
cout << "for 2 run time is: " << (double)(endTime2 - startTime2) / CLOCKS_PER_SEC << "s" << endl;
cout << endl;
vector<Person> vec3;
vec3.reserve(count);
double startTime3 = clock();//3计算开始
for(int i = 0; i < count; i++)
{
Person person(i, i, name);
vec3.emplace(vec3.begin() + i, person);
}
double endTime3 = clock();//3时间结束
cout << "vec3.size=" << vec3.size() << " vec3.capacity=" << vec3.capacity() << endl;
vec3.clear();
cout << "for 3 run time is: " << (double)(endTime3 - startTime3) / CLOCKS_PER_SEC << "s" << endl;
cout << endl;
}
int main()
{
//int = [-2147483648, 2147483647]
insert_emplace_reserve_Test();
cout << endl;
cout << "Hello World!" << endl;
return 0;
}
上一篇: matplotlib基础绘图
下一篇: matplotlib之添加子图
推荐阅读
-
Python3.4学习笔记之常用操作符,条件分支和循环用法示例
-
Oracle数据库学习之查询的嵌套、事务控制语言、集合操作符和SQL函数讲解
-
c/c++ 标准顺序容器 之 push_back,push_front,insert,emplace 操作
-
C++STL之Vector向量详解,用法和例子 一起学习 一起加油
-
SQL学习之CURD操作(INSERT语句)
-
Python七天学习之Day04——循环和函数的相关基础操作
-
学习记录[email protected]操作复选框和下拉列表之选择、判断是否被选中、设置默认选中
-
最新版本深度学习框架Mxnet和gluonts报错不配(MXNetError: vector::_M_range_insert)
-
Oracle数据库学习之查询的嵌套、事务控制语言、集合操作符和SQL函数讲解
-
MySQL学习之浅析联结查询和集合操作