正如标题所说,我正在寻找一种方法来对矢量进行排序,而无需修改原始矢量.我的第一个想法当然是在排序之前创建一个向量副本,例如:
std::vector<int> not_in_place_sort(const std::vector<int>& original)
{
auto copy = original;
std::sort(copy.begin(), copy.end());
return copy;
}
Run Code Online (Sandbox Code Playgroud)
但是,也许有一种更有效的方法来使用C++标准算法执行排序(可能是sort和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.
}
Run Code Online (Sandbox Code Playgroud)
在此之后,indexofarray[]元素将是0, 2, 3, 1,而intarray[]不会改变.
使用partial_sort_copy。这是一个例子:
vector<int> v{9,8,6,7,4,5,2,0,3,1};
vector<int> v_sorted(v.size());
partial_sort_copy(begin(v), end(v), begin(v_sorted), end(v_sorted));
Run Code Online (Sandbox Code Playgroud)
现在,v保持不变,但是v_sorted包含{0,1,2,3,4,5,6,7,8,9}。
| 归档时间: |
|
| 查看次数: |
1456 次 |
| 最近记录: |