Copying the data from the vector to the set will be slower, because it will involve creating a data structure on the heap (typically a red-black tree), while sorting can be done in-place (effectively using the stack as a temporary data store).
#include <iostream>
#include <vector>
#include <set>
size_t gAllocs;
size_t gDeallocs;
void * operator new ( size_t sz ) { ++gAllocs; return std::malloc ( sz ); }
void operator delete ( void *pt ) { ++gDeallocs; return std::free ( pt ); }
int main () {
gAllocs = gDeallocs = 0;
std::vector<int> v { 8, 6, 7, 5, 3, 0, 9 };
std::cout << "Allocations = " << gAllocs << "; Deallocations = " << gDeallocs << std::endl;
std::set<int> s(v.begin(), v.end());
std::cout << "Allocations = " << gAllocs << "; Deallocations = " << gDeallocs << std::endl;
std::sort ( v.begin(), v.end ());
std::cout << "Allocations = " << gAllocs << "; Deallocations = " << gDeallocs << std::endl;
return 0;
}
On my system (clang, libc++, Mac OS 10.8), this prints:
$ ./a.out
Allocations = 1; Deallocations = 0
Allocations = 8; Deallocations = 0
Allocations = 8; Deallocations = 0
Building the set takes 7 memory allocations (one per entry). Sorting the vector takes none.