c++ - insert performance sort data in list and vector -
in principle , practice book of bjarne stroustrup there exercise in chapter 20 asks insert random value in vector , list in sort way (experiment suggested jhon bentley)
this code (if there better way doing sorry )
#include <vector> #include <list> #include <iostream> #include <ctime> #include <random> #include <chrono> using namespace std; template<typename iter, typename t> int find_index(iter start, iter end, const t& value) { int index = 0; while (start != end) { while (start!=end && value >= *start) { ++index; ++start; } return index; } return -1; } template<typename iter> void print(iter first,iter end) { while (first != end) { cout << *first << endl; first++; } } int generate_random(int min, int max) { random_device device; mt19937 generator{ device() }; uniform_int_distribution<int> d{ min,max }; return d(generator); } int main() { int n = 1000; vector<int> vec; list<int> list; auto start = chrono::system_clock::now(); (size_t = 0; i<n; i++) { int value = generate_random(1, n); int index = find_index(vec.begin(), vec.end(), value); if (index == -1) vec.insert(vec.begin(), value); else vec.insert(vec.begin() + index, value); } auto end = chrono::system_clock::now(); print(vec.begin(), vec.end()); cout << "time: " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " milliseconds" << endl; system("pause"); start = chrono::system_clock::now(); (size_t = 0; < n; i++) { int value = generate_random(1, n); int index = find_index(list.begin(), list.end(), value); if (index == -1) list.insert(list.begin(), value); else { auto p = list.begin(); (size_t = 0; < index; i++) { p++; } list.insert(p, value); } } end = chrono::system_clock::now(); print(list.begin(), list.end()); cout << "time: " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " milliseconds" << endl; system("pause"); }
and output is:
n 1000 5000 10000 100000 vec 250ms 4s 16s laptop committed suicide list 600ms 15s 63s laptop committed suicide
vec fast list why book says: << performance reasons, wouldn't use insert , erase int middle of 100000 element vector; list (and map) better.>>
did write code in wrong way?
Comments
Post a Comment