排序并跟踪元素 [英] Sort and keep track of elements

查看:99
本文介绍了排序并跟踪元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只知道,我现在在谈论C ++.

Just to know, I'm talking C++ now.

假设我有一个数组A = {4, 1, 5, 2, 3}并在A_sorted = {1, 2, 3, 4, 5}中对其进行排序.我想保留以下信息:排序后的数组A_sorted中的元素e(来自数组A)在哪里?例如:在A(5)中具有索引2的元素现在在A_sorted中具有索引4.

Suppose I have an array A = {4, 1, 5, 2, 3} and sort it in A_sorted = {1, 2, 3, 4, 5}. I would like to keep the following information: where is now element e (from array A) in the sorted array A_sorted? e.g.: element with index 2 in A (5) has now index 4 in A_sorted.

问题更像是:一个人可以使用STL来实现这一目标吗?

The question is more like: can one use STL to achieve this?

推荐答案

尚无现成的功能来实现此目的,但是有一些变通方法.例如,您可以保留用户定义的结构数组,这些结构也包含原始位置:

There's no off-the-shelf functionality to achieve this, but there are work-arounds. You can, for example, keep an array of user-defined structs that also contain the original position:

A = { {4,0}, {1,1}, {5,2}, {2,3}, {3,4}}

然后使用自定义比较器函数对该函数进行排序,该函数按值而不是原始索引进行排序.

And then sort this using a custom comparator function that sorts by the value and not the original index.

A_sorted = {{1,1}, {2,3}, {3,4}, {4,0}, {5,2}}

这篇关于排序并跟踪元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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