在阅读代码时,发现有使用size()==0判断是否容器为空的,而从<<Effective STL>>上看到size()不能保证常数时间,建议使用empty()替换。因此我做了一个实验,发现size()并不能保证常数时间,但empty可以保证。
代码语言:javascript复制/**
测试vector、list、set调用empty和size的耗时是否为常数,
结论:empty()的调用时间都是常数,list的size()的调用时间非常数
使用建议:判断成员是否为空时使用empty(),而非size() == 0
input COUNT:100000(10W) 1000000(100W)
output
member count is:1000000
test vector.empty():
cost time(ms):0
test vector.size():
cost time(ms):0
---------------------
test list.empty():
cost time(ms):0
test list.size():
cost time(ms):8
---------------------
test set.empty():
cost time(ms):0
test set.size():
cost time(ms):0
---------------------
member count is:10000000
test vector.empty():
cost time(ms):0
test vector.size():
cost time(ms):0
---------------------
test list.empty():
cost time(ms):0
test list.size():
cost time(ms):79
---------------------
test set.empty():
cost time(ms):0
test set.size():
cost time(ms):0
---------------------
*/
#include <iostream>
#include <vector>
#include <set>
#include <list>
#include <sys/time.h>
using namespace std;
typedef unsigned long long ull;
#define COST_TIME_START
{
timeval start;
gettimeofday(&start, NULL);
#define COST_TIME_END
timeval end;
gettimeofday(&end, NULL);
cout << "cost time(ms):" << ((end.tv_sec*1000 end.tv_usec/1000) - (start.tv_sec*1000 start.tv_usec/1000)) << endl;
}
int main (int argc, char **argv) {
cout << "member count is:" << COUNT << endl;
vector<ull> v;
v.assign(COUNT, 0);
cout << "test vector.empty():" << endl;
COST_TIME_START
v.empty();
COST_TIME_END
cout << "test vector.size():" << endl;
COST_TIME_START
v.size();
COST_TIME_END
cout << "---------------------" << endl;
list<ull> l;
l.assign(COUNT, 0);
cout << "test list.empty():" << endl;
COST_TIME_START;
l.empty();
COST_TIME_END;
cout << "test list.size():" << endl;
COST_TIME_START;
l.size();
COST_TIME_END;
cout << "---------------------" << endl;
set<ull> s;
for (ull i = 0; i < COUNT; i) {
s.insert(i);
}
cout << "test set.empty():" << endl;
COST_TIME_START
s.empty();
COST_TIME_END
cout << "test set.size():" << endl;
COST_TIME_START
s.size();
COST_TIME_END
cout << "---------------------" << endl;
return 0;
}