I'm trying to figure out a good container for my needs. I wont have many insertions, but look up needs to be as fast as possible. I figure then to sequence container and then sort it after insertion. I'm second guessing myself as I right this, hmm...
Anyway, right now I am trying to figure out what container sorts the fastest. I have this Windows dependent code, which basically says:
Create an array of random numbers,
copy the array into a vector using push_back (no reserved space)
sort the vector
copy the array into a forward_list
sort the forward_list
The Windows dependency is for counting milliseconds of the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
#include <Windows.h>
#include <iostream>
#include <forward_list>
#include <vector>
#include <algorithm>
#include <random>
#define AMT 500000
#define MSEC GetTickCount()
typedef DWORD timeType;
void testVector(int *arr)
{
std::vector<int> v;
std::cout << "Vector Insertion: ";
timeType start = MSEC;
for (int i = 0; i < AMT; i++)
v.push_back(arr[i]);
timeType end = MSEC;
timeType total = end - start;
std::cout << total << std::endl;
std::cout << "Vector Sort: ";
start = MSEC;
std::sort(v.begin(), v.end());
end = MSEC;
total += end - start;
std::cout << end - start << std::endl;
std::cout << "Vector Total: " << total << std::endl;
}
void testList(int *arr)
{
std::forward_list<int> l;
std::cout << "List Insertion: ";
timeType start = MSEC;
for (int i = 0; i < AMT; i++)
l.push_front(arr[i]);
timeType end = MSEC;
timeType total = end - start;
std::cout << total << std::endl;
std::cout << "List Sort: ";
start = MSEC;
l.sort();
end = MSEC;
total += end - start;
std::cout << end - start << std::endl;
std::cout << "List Total: " << total << std::endl;
}
int main(void)
{
std::random_device rand;
int *arr;
arr = new int[AMT];
for (int i = 0; i < AMT; i++)
arr[i] = rand() % (AMT);
testVector(arr);
testList(arr);
std::cin.get();
delete [] arr;
return 0;
}
|
The output being:
Vector Insertion: 218
Vector Sort: 1079
Vector Total: 1297
List Insertion: 1531
List Sort: 84282
List Total: 85813
|
How in the world is the forward_list so bad? I thought this was something it would out perform the vector in.
Edit: Do I need a more complex data type to sort? Or perhaps a class with complicated constructors?