std::sort and custom swap function

泪湿孤枕 提交于 2019-12-10 10:47:33

问题


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);

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?


回答1:


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.




回答2:


You should specialize std::sort using your custom "comparator".

template <class RandomAccessIterator, class Compare>
void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp );

By default sort uses a standard comparator which just compares the elements referenced by the given iterators.

Using the custom Compare you may override this. Note that it's not a function (in C++ generally you may not pass a function as a template parameter). It's a class. You pass an object of this class to sort, whereas this object should implement the following operator:

bool operator () (const Type1 &a, const Type2 &b);

So, you may invoke sort for array of your double's. Your comparator should have pointers to the beginning of both your arrays: double and int.

In case with arrays the iterator resolves into a pointer to an array element. Using the array starting address you may convert it into an index, and use it to access the second array.



来源:https://stackoverflow.com/questions/12029779/stdsort-and-custom-swap-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!