【发布时间】:2012-11-28 16:28:23
【问题描述】:
我有一个函数,它接受两个大小相同的向量作为参数:
void mysort(std::vector<double>& data, std::vector<unsigned int>& index)
{
// For example :
// The data vector contains : 9.8 1.2 10.5 -4.3
// The index vector contains : 0 1 2 3
// The goal is to obtain for the data : -4.3 1.2 9.8 10.5
// The goal is to obtain for the index : 3 1 0 2
// Using std::sort and minimizing copies
}
如何解决这个问题,尽量减少所需副本的数量?
一种明显的方法是制作std::pair<double, unsigned int> 的单个向量并通过[](std::pair<double, unsigned int> x, std::pair<double, unsigned int> y){return x.first < y.first;} 指定比较器,然后将结果复制到两个原始向量中,但效率不高。
注意:函数的签名是固定的,我不能传递std::pair的单个向量。
【问题讨论】:
-
副本不是更容易编写,而且时间复杂度更高。
-
我不知道为什么你会想要一个不再包含对现在排序数组的有效偏移量的索引。是否只是为了知道元素在排序之前 位于哪些插槽中?
-
@WhozCraig:这被称为“从排列”。这种情况下的问题是对值进行排序,并为排序后的数组生成一个“从排列”,即 original 索引数组。这是一个很常见的问题。
-
是
index保证是[0,1,2,...],或者这只是一个例子?
标签: c++ algorithm sorting c++11