[英]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?鉴于它们具有相同的大小,大小为 4 字节的元素的向量排序会比说 128 字节的元素更快吗? Do I have to index them and sort the indicies manually or does std::sort does it under the hood for me?我是否必须对它们进行索引并手动对索引进行排序,或者 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?鉴于它们具有相同的大小,大小为 4 字节的元素的向量排序会比说 128 字节的元素更快吗?
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.这取决于 CPU 架构,但是当std::sort
移动整个对象时,期望更大的对象排序更慢(假设其他一切都相同)是很有可能和合理的。
Do I have to index them and sort the indicies manually or does std::sort does it under the hood for me?我是否必须对它们进行索引并手动对索引进行排序,或者 std::sort 是否为我在后台进行?
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.如果要对索引而不是对象进行排序,则需要明确地执行此操作-将std::sort
应用于索引容器,而不是实际对象,而是使用使用索引指向的实际对象的比较器。 Again std::sort
moves actual objects, in this case objects would be indexes.再次std::sort
移动实际对象,在这种情况下,对象将是索引。
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.现在您的索引将按value
的升序排序,但objects
容器将保持不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.