欢迎光临散文网 会员登陆 & 注册

读书笔记《effective stl》item4: 调用empty而不是检查size()是否为0

2022-01-18 02:50 作者:LogByMax  | 我要投稿

因为empty的效率比size()高。


#include <iostream>

#include <vector>

#include "time.h"

using namespace std;

typedef vector<int> VI;

template<class T>

T push_int_containers(int large, int small, T c)

{

    for (int i = large; i>small ; i--)

    {

        c.push_back(i);

    }

    return c;

template<class T>

void print_containers(string name,T c)

{

    cout << "\n" << name <<" : ";

    for (auto i = c.begin(); i != c.end(); ++i)

    {

        cout << *i << " ";

    }

    cout << "\n";

}

int main()

{

    VI v1;

    v1 = push_int_containers(100,1,v1);

    

    auto b1 = clock();

    cout << (v1.size() == 0) << "\n";

    auto e1 = clock();

    cout << "the time of (v1.size() == 0) is " << e1 - b1 << "\n";

    

    auto b2 = clock();

    cout << (v1.empty() == true) << "\n";

    auto e2 = clock();

    cout << "the time of (v1.empty() == true) is " << e2 - b2 << "\n";

    

    return 0;

}

输出结果:

0

the time of (v1.size() == 0) is 31

0

the time of (v1.empty() == true) is 2


=END=

读书笔记《effective stl》item4: 调用empty而不是检查size()是否为0的评论 (共 条)

分享到微博请遵守国家法律