SoFunction
Updated on 2025-04-06

c++ std::sort uses custom comparison function sorting method

Use sort to sort elements in container

  • The std::sort() function is specifically used to sort elements within a specified range in a container or ordinary array. The sorting rules are sorted in ascending order by default by the size of the element value.
  • sort() only provides support for array, vector, and deque containers
  • You can customize the sorting function
#include <iostream>
#include <vector>
#include <algorithm>

// Define the pair type
typedef std::pair<uint32_t, uint64_t> PairType;

// Comparator function to compare pairs based on the second element (value)
bool comparePairs(const PairType& p1, const PairType& p2) {
    return  > ;
}

int main() {
    // Create the vector of pairs
    std::vector<PairType> vec = {
        {1, 100},   // idx=1, value=100
        {2, 50},    // idx=2, value=50
        {3, 200},   // idx=3, value=200
        // Add more pairs here if needed
    };

    // Sort the vector using the comparator function
    std::sort((), (), comparePairs);

    // Output the sorted vector
    for (const auto& pair : vec) {
        std::cout << "idx: " <<  << ", value: " <<  << std::endl;
    }

    return 0;
}

comparePairs is our custom function, sort the third place

 std::sort((), (), comparePairs);

How to call custom member functions in class to sort

typedef std::pair&lt;uint32_t, uint64_t&gt; PairType;

bool MySort::comparePairs(const PairType&amp; p1, const PairType&amp; p2) {
    return  &gt; ;
}

bool MySort::sort_fun(vector&lt;PairType&gt; vec)
{
    std::sort((), (), comparePairs); //Report an error}

Visual Studio error:

C3867   “MySort::compareParis”: non-standard syntax; please use "&" to create a pointer to a member
C2672   “std::sort”: No matching overloaded function was found
C2780   “void std::sort(const _RanIt,const _RanIt)”: 2 parameters should be entered, but 3 parameters should be provided

Cause of error

This error is because when using std::sort(), a member function pointer is passed, not a normal function pointer

Solution

Using Lambda expressions:

Modified code:

typedef std::pair&lt;uint32_t, uint64_t&gt; PairType;

bool MySort::comparePairs(const PairType&amp; p1, const PairType&amp; p2) {
    return  &gt; ;
}

bool MySort::sort_fun(vector&lt;PairType&gt; vec)
{
	// Define Lambda expressions	auto sortLambda = [this](const PairType&amp; p1, const PairType&amp; p2) {
        return this-&gt;comparePairs(a, b);
    };
    
	std::sort((), (), sortLambda); 
}

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.