我有一个功能,需要对给定的元素进行排序。原始矢量一定不能更改,因此我需要该矢量的浅表副本。由于我不需要复制元素本身,因为它们只能被读取,所以我决定制作一个指针向量。目前,我有一个简单的循环来填充矢量,但是我想知道是否存在内置/标准解决方案,甚至可能更快。
void calcFindMinLeftAndSort(std::vector<Location>& locationsComplete, std::vector<Location*>& locationsSorted) {
// ...
// copy data in new array, to keep the original untouched
locationsSorted.reserve(locationsComplete.size());
// looking for locationsSorted.assign(&elements)
// yes, I could use for each instead
for (size_t i = 0; i < locationsComplete.size(); i++)
locationsSorted.emplace_back(&locationsComplete[i]);
// sort
std::sort(locationsSorted.begin(), locationsSorted.end(), compare);
}
Run Code Online (Sandbox Code Playgroud)
附加信息:locationsComplete向量按特定顺序排序,不得更改。该矢量在应用程序运行期间不会改变。排序后的locationSorted向量被另一个函数使用了一次(可以在同一函数中使用,但这种方式看起来更清晰)。返回下一个函数的结果后,locationsSorted向量将退役。因此,它可以看作是寿命很短的临时载体。
您可以做的,并且可能想做的,根本不使用指针 - 只需将索引集排序到locationsCompare
,使用比较函数在原始区域中查找值。使用 C++11 轻松搞定:
template <typename T>
std::vector<size_t> get_sorted_positions(const std::vector<T> &v)
{
std::vector<size_t> indices(v.size());
std::iota(indices.begin(), indices.end(), 0); // indices now holds 0 ... v.size()-1
std::sort(indices.begin(), indices.end(),
[&v](size_t i_1, size_t i_2) { return v[i_1] < v[i_2]; }
);
return indices;
}
Run Code Online (Sandbox Code Playgroud)
笔记:
std::vector<typename Container::size_type>
);或采用一对迭代器;或在 C++20 中 - 取任意范围。但索引仍然是一个向量。 归档时间: |
|
查看次数: |
119 次 |
最近记录: |