简体   繁体   中英

Does the size of the element matter to the speed of std::sort?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM