std ::排序和自定义交换函数 [英] std::sort and custom swap function

查看:233
本文介绍了std ::排序和自定义交换函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个 pair< double,int> 数组,我使用一个简单的自定义比较函数,例如

I currently have an array of pair<double, int> which I sort using a simple custom comparator function e.g.

// compare by first
int sort_index_lcomparator(const pair<double, int>& a, const pair<double, int>& b) {
    return a.first < b.first;
}
// then sort simply like
pair<double, int> arr[size];
std::sort(arr, arr + size, sort_index_lcomparator);



我实际上对索引顺序感兴趣,而不是排序的双精度。我的问题是,我想改变从这个结构,而是一个两个数组的结构,而不是结构的数组,我想优化局部性和自动矢量化,但在这种情况下,我需要一个重载 swap 具体附加到类型。我想我需要一些重新定义 swap double 类型,并保持两个数组同步custom swap 。有没有办法在有限范围内以这种方式覆盖 swap

I'm actually interested in the index order and not in the sorted doubles. My problem is that I would like to change away from this structure and have instead a struct of two arrays rather than an array of a struct i.e. I would like to optimize for locality and auto-vectorization but in this case I need an overloaded swap which is attached to a type specifically. I guess I would need something along the lines of redefining swap for the double type and keep both arrays in sync in such custom swap. Is there a way to "override" swap in such a manner within a limited scope?

推荐答案

我有一个建议:使索引数组排序,并将值保存为全局数组。从此开始:基于接受指数的比较器进行排序,但实际上是根据值进行比较。

I have one proposal for you: make the index array the one you sort and keep the values as global array. From then on: sort based on comparator that accepts indices, but actually compares based on the values.

这篇关于std ::排序和自定义交换函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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