本篇学习list添加元素操作
push_back:将元素添加到容器末尾
emplace_back:在容器末尾就地构造元素
push_front:插入元素到容器起始
emplace_front:在容器头部就地构造元素
resize:改变容器中可存储元素的个数
代码实现:
#include <list>
#include <iostream>
#include <time.h>
using namespace std;
class Person3
{
public:
Person3(string name):
m_strName(name)
{
}
string m_strName;
};
void addElement()
{
list<Person3> list1;
string strName = "《出塞(王昌龄)》秦时明月汉时关,万里长征人未还。但使龙城飞将在,不教胡马度阴山。";
Person3 person(strName);
//int = [-2147483648, 2147483647]
const int count = 214748;//2147483648
//1.push_back:将元素添加到容器末尾
double startTime1 = clock();//1计算开始
for(int i = 0; i < count; i++)//214748
{
list1.push_back(strName);
}
double endTime1 = clock();//1时间结束
list1.clear();
cout << "for 1 run time is: " << (double)(endTime1 - startTime1) / CLOCKS_PER_SEC << "s" << endl;
cout << endl;
//2.emplace_back:在容器末尾就地构造元素
list<Person3> list2;
double startTime2 = clock();//2计算开始
for(int i = 0; i < count; i++)//214748
{
list2.emplace_back(strName);
}
double endTime2 = clock();//2时间结束
list2.clear();
cout << "for 2 run time is: " << (double)(endTime2 - startTime2) / CLOCKS_PER_SEC << "s" << endl;
cout << endl;
//3.push_front:插入元素到容器起始
list<Person3> list3;
double startTime3 = clock();//1计算开始
for(int i = 0; i < count; i++)//214748
{
list3.push_front(strName);
}
double endTime3 = clock();//1时间结束
list3.clear();
cout << "for 3 run time is: " << (double)(endTime3 - startTime3) / CLOCKS_PER_SEC << "s" << endl;
cout << endl;
//4.emplace_front:在容器头部就地构造元素
list<Person3> list4;
double startTime4 = clock();//2计算开始
for(int i = 0; i < count; i++)//214748
{
list4.emplace_front(strName);
}
double endTime4 = clock();//2时间结束
list4.clear();
cout << "for 4 run time is: " << (double)(endTime4 - startTime4) / CLOCKS_PER_SEC << "s" << endl;
cout << endl;
//5.resize:改变容器中可存储元素的个数
list<int> list5;
cout << "list5.empty = " << list5.empty() << " list5.size = " << list5.size() << endl;
cout << "list5的值为:" << endl;
list5 = {31, 32, 33, 34};
for(auto &val: list5)
cout << val << "\t";
cout << endl;
cout << "list5的值为:" << endl;
list5.resize(3);
for(auto &val: list5)
cout << val << "\t";
cout << endl;
list5.resize(5);
cout << "list5的值为:" << endl;
for(auto &val: list5)
cout << val << "\t";
cout << endl;
cout << "list5的值为:" << endl;
list5.resize(7, 67);
for(auto &val: list5)
cout << val << "\t";
cout << endl;
cout << endl;
}
int main()
{
addElement();
cout << endl;
cout << " Hello World!" << endl;
return 0;
}
运行结果:
从以上结果可以看出,添加元素,emplace_front/emplace_back比push_front/push_back效果要高很多,原理是emplace_front/emplace_back在元素后原位构造元素,省掉拷贝的过程。
resize重新设置list容器的大小,如果设置的值n小于当前容器的容量,则只取容器前n个元素,如果n大于当前容器的容量,则将其扩充为容量n,如果没有指定填充值,采用0填充,指定默认值则采用默认值填充。
参考:
http://www.cplusplus.com/reference/list/list/
https://zh.cppreference.com/w/cpp/container/list