std::sort and custom swap function

ε祈祈猫儿з 提交于 2019-12-06 14:00:59

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.

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.

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