如何不对数组的元素进行排序,而是对数组的索引进行排序?
How do I sort not the elements of an array, but it's indexes?
所以我有一个类似的数组:
int array[]={2, 4, 3, 1};
我想按降序排序,但要获得原始索引,这样: {1,2,0,3}我如何解决此问题,以便与任何大小的数组一起使用?另外,是否有不需要C 11的解决方案?
谢谢!
我会去做这样的事情:
std::vector<std::pair<int, int>> temp ;
int idx = 0 ;
for (auto x : array)
temp.push_back(std::make_pair(x, idx++)) ;
std::sort(temp.begin(), temp.end()) ;
您可以轻松地摆脱(此处使用的C 11结构)的范围。无需定义STD :: PAIR的比较,默认一个可以。
如果我正确理解您,您想获得一个索引的索引列表。一种解决方案是创建一个无序的所有元素索引列表并对其进行排序。
int array[] = {2, 4, 3, 1};
int indices[] = {0, 1, 2, 3};
std::sort(indices, indices + 4, [&](int a, int b) {
return array[b] < array[a];
});
由于您要求提供一个非C 11-way,因此您可以在lambda表达式上工作,如下所示:
int array[] = {2, 4, 3, 1};
int indices[] = {0, 1, 2, 3};
struct {
int *array;
bool operator()(int a, int b) const
{
return this->array[b] < this->array[a];
}
} customLess = {array};
std::sort(indices, indices + 4, customLess);
两个实现都将对indices
的值进行排序,但不是 array
本身。结果看起来如下所示:
array == {2, 4, 3, 1}
indices == {1, 2, 0, 3}
有一个棘手,简单的解决方法:首先,您有一个未分组的数组,因此创建索引 {0, 1, 2, 3}
的数组,然后使用循环对值进行分类,同时交换数组的元素根据值数组的索引:
int array[] = {2, 4, 3, 1};
int indexes[] = {0, 1, 2, 3};
for(int i(0); i < 4; i++){
for(int j(i + 1); j < 4; j++){
if(array[i] < array[j]){
//sorting values
array[i] ^= array[j];
array[j] ^= array[i];
array[i] ^= array[j];
// sorting indexes
indexes[i] ^= indexes[j];
indexes[j] ^= indexes[i];
indexes[i] ^= indexes[j];
}
}
}
cout << endl;
for(int i = 0; i < 4; i++)
cout << array[i] << ", ";
cout << endl;
for(int i = 0; i < 4; i++)
cout << indexes[i] << ", ";
我使用xor
对数组进行排序,但是您可以使用临时变量:
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
tmp = indexes[i];
indexes[i] = indexes[j];
indexes[j] = tmp;
输出:
4, 3, 2, 1,
1, 2, 0, 3,
您必须在某个地方保存初始索引。一种解决方案是与结构。有点像这样:
struct IndexInt
{
int index;
int value;
} typename IndexInt_t
IndexInt_t array[]={{1,2}, {2,4}, {3,3}, {4,1}};
现在您可以在array[i].value
之后进行排序,并通过array[i].index
访问原始索引。
相关文章:
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 显示错误输出的简单数组排序程序
- 为什么我的排序算法会更改数组值
- 为什么我需要C++中不同的排序格式来对这个USACO代码上的数组和优先级队列进行排序
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 合并排序不排序自创建数组类 c++
- 带有枚举方向/类型的气泡排序结构数组
- 为什么指针在对二维数组进行排序时无法正常工作?
- 排序并行数组
- 如何在数组 c++ 中对字符串进行排序
- 为什么在此排序算法实现中,向量明显比数组慢?
- 如何对不在数组中的变量进行排序?
- C++数组与向量排序(在我的情况下,向量比数组慢~2.5倍(无优化))
- 按字母顺序对结构内数组变量中的名称进行排序
- 使用排序函数 c++ 对字符数组进行排序
- 使用 std::sort 对二维 c 数组进行排序
- 使用STL对用户输入数组进行排序的错误有什么解决方案吗?
- 使用 std::sort 对 C 样式的 2D 数组进行部分排序
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- 对 0 、1 和 2 的数组进行排序