本文共 2694 字,大约阅读时间需要 8 分钟。
在进行多目标跟踪显示轨迹时,需要将固定长度的历史轨迹存储并画线显示;因为固定长度,所以需要对数据的头部和尾部都进行操作。当前考虑的存储方式有vector和deque。vector的优势是对中间的操作速度快,deque优势是对两端的操作速度快(百度搜索结果),为综合考虑索引、赋值、删除等操作,现在做以下测试。分别是:
#include#include #include #include using namespace std;int size = 1000000;vector vecint;deque queint;clock_t t0, t1;float vectorTest(){ int size = 1000000; clock_t t_0 = clock(); for (size_t i = 0; i < size; i++) { vecint.push_back(i); } clock_t t_1 = clock(); cout << "vector尾部插入操作1000000用时:" << t_1 - t_0 << endl; //953 return t_1 - t_0;}float dequeTest(){ int size = 1000000; clock_t t_0 = clock(); for (size_t i = 0; i < size; i++) { queint.push_back(i); } clock_t t_1 = clock(); cout << "deque尾部插入1000000操作用时:" << t_1 - t_0 << endl; //833 return t_1 - t_0;}float foreachVector(){ cout << "vector.size():" << vecint.size() << endl; clock_t t_1 = clock(); for (int i = 0; i < vecint.size(); i++) { int a = vecint[i]; } clock_t t_2 = clock(); cout << "vector索引遍历用时:" << t_2 - t_1 << endl; //262 return t1 - t0;}float foreachVector3(){ cout << "vector.size():" << vecint.size() << endl; clock_t t_1 = clock(); for (auto i:vecint) { int a = i; } clock_t t_2 = clock(); cout << "vector遍历3用时:" << t_2 - t_1 << endl; //262 return t1 - t0;}float foreachDeque(){ clock_t t_0 = clock(); for (int i = 0; i < vecint.size(); i++) { int a = queint[i]; } clock_t t_1 = clock(); cout << "deque索引遍历用时:" << t_1 - t_0 << endl; // 1055 return t_1 - t_0;}float foreachDeque2(){ clock_t t_0 = clock(); for (auto i = queint.begin(); i != queint.end(); i++) { int a = *i; } clock_t t_1 = clock(); cout << "deque迭代器遍历用时:" << t_1 - t_0 << endl; // 1061 return t_1 - t_0;}void popFrontVector(){ int count = 0; clock_t t_0 = clock(); for (int i = 0; i < 100; i++) { auto ptr = vecint.erase(vecint.begin()); // cout << (int)&ptr << endl; //打印显示该值一直是固定值 count++; } clock_t t_1 = clock(); cout << "操作" << count << "次" << "删除头部元素vector用时:" << t_1 - t_0 << endl; // 一百次用时61}void popFrontDeque(){ int count = 0; clock_t t_0 = clock(); for (int i = 0; i < 10000; i++) { queint.pop_front(); count = i; } clock_t t_1 = clock(); cout <<"操作"< <<"次"<< "删除头部元素deque用时:" << t_1 - t_0 << endl; // 1万次用时7}void main(){ vectorTest(); dequeTest(); foreachVector(); foreachDeque(); foreachDeque2(); foreachVector3(); popFrontVector(); popFrontDeque(); system("pause"); return;}
结果如下:
结论:
1. 追加元素操作,vector速度更快; 2. deque使用迭代器或索引对所有元素遍历,速度差不多;vector使用索引遍历速度比使用(auto a:vector)的速度稍慢; 3. 对头部元素操作速度,deque远远快于vector; 考虑到在实际使用中遍历的使用频率以及消耗时长更多,最终采用了vector进行数据存储;初学C++,很多问题了解并不是很全面,如有问题还请及时指正,谢谢。
转载地址:http://ntnws.baihongyu.com/