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";
}