Reputation: 65
Given that they have the same size, would a vector of an element of size 4 byte sort faster than an element of say 128 bytes? Do I have to index them and sort the indicies manually or does std::sort does it under the hood for me?
Upvotes: 0
Views: 174
Reputation: 44238
Given that they have the same size, would a vector of an element of size 4 byte sort faster than an element of say 128 bytes?
That depends on CPU architecture but it is quite possible and reasonable to expect that bigger objects would be sorted slower (assuming everything else is equal) as std::sort
moves whole objects.
Do I have to index them and sort the indicies manually or does std::sort does it under the hood for me?
If you want to sort indexes instead of objects you need to do that explicitly - apply std::sort
on container of indexes, not actual objects, but use comparator that uses actual objects where indexes point to. Again std::sort
moves actual objects, in this case objects would be indexes.
For example:
struct BigObject {
int value;
// some other data that makes this object big
};
std::vector<BigObject> objects;
// objects is populated with data somehow
std::vector<std::size_t> indexes( objects.size() );
// fill indexes with values from 0 to N-1
std::iota( indexes.begin(), indexes.end(), 0 );
// sort indexes
std::sort( indexes.begin(), indexes.end(), [&objects]( size_t i1, size_t i2 )
{
return objects[i1].value < objects[i2].value;
} );
Now your indexes would be sorted in ascending order of value
but objects
container will be left intact.
Upvotes: 2