C++ Premier Plus 6th edition - Programming excercise - Chapter16 - 9

main.cpp

#include<iostream>
#include<vector> // vector
#include<list> // list
#include<algorithm> // copy() of STL
#include<iterator> // insert_iterator
#include<ctime> // clock_t,clock(),time()
#include<utility> // pair
#include<set> // set
#include<string> // cout string obj
#include<cstdlib> // rand()

using std::vector;
using std::list;
using std::cout;
using std::cin;
using std::copy;
using std::sort;
using std::pair;

// prototype
void Show(double tv, double tl, double tc);
void showFunctor(pair<double, std::string> pa);

int main()
{
    const int size = 10000;// const or not,doesn't matter,vector can change length
    // create vi0
    vector<int> vi0(size);
    std::srand((unsigned)time(0));// seed
    for (int i = 0; i < size; i++)
    {
        vi0[i] = std::rand();
    }

    // create vi,li
    vector<int> vi = vi0;
    list<int> li;
    copy(vi0.begin(), vi0.end(), std::insert_iterator<list<int>>(li, li.end()));

    // count time of vi-sort()
    double tv;
    clock_t start = clock();
    sort(vi.begin(), vi.end());
    clock_t end = clock();
    tv = end - start;

    // count time of li-sort()
    double tl;
    start = clock();
    li.sort();
    end = clock();
    tl = end - start;

    // count time of combined copy-sort-copy
    //    ATTENTION:use li.begin() instead of li.end(),intend to cover original values
    copy(vi0.begin(), vi0.end(), li.begin());
    double tc;
    start = clock();
    copy(li.begin(), li.end(), vi.begin());// copy to
    sort(vi.begin(), vi.end());// sort
    copy(vi.begin(), vi.end(), li.begin());// copy back
    end = clock();
    tc = end - start;

    // show result
    Show(tv,tl,tc);

    cin.get();
}

// below 2 functions made for showing result
void Show(double tv,double tl,double tc)
{
    // connect name and value
    pair<double, std::string> pv(tv, "Time of vi-sort()");
    pair<double, std::string> pl(tl, "Time of li-sort()");
    pair<double, std::string> pc(tc, "Time of combined");
    // store in set
    std::set<pair<double, std::string>> se = { pv,pl,pc };
    // show in sort order
    std::for_each(se.begin(), se.end(), showFunctor);
}

void showFunctor(pair<double, std::string> pa)
{
    cout << pa.second << ": " << pa.first << "\n";
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值