I have a sequence of double (with no duplicates) and I need to sort them. Is filling a vector and then sorting it faster than inserting the values in a set?
Is this question answerable without a knowledge of the implementation of the standard library (and without a knowledge of the hardware on which the program will run) but just with the information provided by the C++ standard?
#include <vector>
#include <set>
#include <algorithm>
#include <random>
#include <iostream>
std::uniform_real_distribution<double> unif(0,10000);
std::default_random_engine re;
int main()
{
std::vector< double > v;
std::set< double > s;
std::vector< double > r;
size_t sz = 10;
for(size_t i = 0; i < sz; i++) {
r.push_back( unif(re) );
}
for(size_t i = 0; i < sz; i++) {
v.push_back(r[i]);
}
std::sort(v.begin(),v.end());
for(size_t i = 0; i < sz; i++) {
s.insert(r[i]);
}
return 0;
}
From the C++ standard, all we can say is that they both have the same asymptotic complexity (
O(n*log(n))).The set may be faster for large objects that can’t be efficiently moved or swapped, since the objects don’t need to be moved more than once. The vector may be faster for small objects, since sorting it involves no pointer updates and less indirection.
Which is faster in any given situation can only be determined by measuring (or a thorough knowledge of both the implementation and the target platform).