保持数组的顺序在检查中C ++ [英] Keeping the order of the array in check in C++

查看:111
本文介绍了保持数组的顺序在检查中C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有很多那些以一种有效的方式排序算法,我想知道 如果有输出数组的顺序排序后的有效的方法。

There are a lot of algorithms that do sorting in an efficient way, and I was wondering if there are efficient ways of outputting the order of the array after sorting.

例如,假设我们有

A [5] = {1,7,5,4,10}

A [0] = 1 A [1] = 7 A [2] = 5 A [3] = 4 A [4] = 10

则排序后它变成

{1,4,5,7,10} 的,而是 {1,4,5,7,10} 作为输出,

假设我们希望 {0,3,2,1,4} 作为输出

(如 {1 = [0],4 =一个[3],5 =一个[2],7 =一个[1],10 =一个[4]}

有没有做这件事的时候数组是真正大的有效方式?

Is there an efficient way of doing it when the array is really large?

(或者一些数据结构,帮助做这件事?)

(or some data structure that helps doing it?)

任何帮助将是很大的AP preciated。

Any help would be greatly appreciated.

推荐答案

它可以很容易地的std ::对取值的向量做:

It can easily be done with an vector of std::pairs:

std::vector<std::pair<int,std::size_t>> toSort = {{value1,0},{value2,1}};
std::sort(toSort.begin(),toSort.end());

那么你可以只输出 toSort [I]。第二个的向量的所有元素。需要注意的是的std ::对重载运营商的LT; 在一个合理的方式,也就是为什么你不需要提供自定义比较功能。这是一样高效,稳定的排序,以及同等价值的元素将保持原来的顺序。

Then you can just output toSort[i].second for all elements of the vector. Note that std::pair overloads operator< on a sensible way which is why you do not need to provide a custom compare function. This is just as efficient as a stable sort, and elements of the same value will keep their original order.

这篇关于保持数组的顺序在检查中C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆