排除一个矢量的最佳方法是什么?(What is the best way to sort a vector leaving the original one unaltered?)

正如标题所说,我正在寻找一种排序矢量而不修改原始矢量的方法。 我的第一个想法当然是在排序之前创建一个向量的副本,例如:

std::vector<int> not_in_place_sort(const std::vector<int>& original) { auto copy = original; std::sort(copy.begin(), copy.end()); return copy; }

但是,也许有一种更有效的方式来使用C ++标准算法执行排序(可能是sort和transform的组合)?

As the title says, I'm looking for a way to sort a vector without modifying the original one. My first idea is of course to create a copy of the vector before the sort, e.g.:

std::vector<int> not_in_place_sort(const std::vector<int>& original) { auto copy = original; std::sort(copy.begin(), copy.end()); return copy; }

However, maybe there is a more efficient way to perform the sort using C++ standard algorithm (maybe a combination of sort and transform?)

最满意答案

这是我的最爱。 对索引进行排序而不是原始数组/矢量本身。

#include <algorithm> int main() { int intarray[4] = { 2, 7, 3, 4 };//Array of values //or you can have vector of values as below //std::vector<int> intvec = { 2, 7, 3, 4 };//Vector of values int indexofarray[4] = { 0, 1, 2, 3 };//Array indices std::sort(indexofarray, indexofarray + 4, [intarray](int index_left, int index_right) { return intarray[index_left] < intarray[index_right]; });//Ascending order. //have intvec in place of intarray for vector. }

在此之后, indexofarray[]元素将为intarray[] ,而intarray[]不变。

Here is my favorite. Sort an index and not the original array/vector itself.

#include <algorithm> int main() { int intarray[4] = { 2, 7, 3, 4 };//Array of values //or you can have vector of values as below //std::vector<int> intvec = { 2, 7, 3, 4 };//Vector of values int indexofarray[4] = { 0, 1, 2, 3 };//Array indices std::sort(indexofarray, indexofarray + 4, [intarray](int index_left, int index_right) { return intarray[index_left] < intarray[index_right]; });//Ascending order. //have intvec in place of intarray for vector. }

After this, indexofarray[] elements would be 0, 2, 3, 1, while intarray[] is unchanged.

更多推荐