Home > OS >  Understand the sorting of a vector of pair (int and pointer to object)
Understand the sorting of a vector of pair (int and pointer to object)

Time:09-28

I have a vector of pair defined as follows:

vector<pair<int, myClass *>> myVector;

The vector is sorted using the following:

sort(myVector.begin(), myVector.end());

This code is not mine and everything is working fine.

The only thing I don't get and I would like to understand is:

When I have two elements of my vector with the same int value as first, how the sorting is done ? On which criteria ? I was thinking first, it's based on the value of the pointer to my object in the pair. But I can't see it.

I wan't to understand it because I need to reproduce this behavior (the sorting) on a demonstrator on Matlab.

Thank for your help.

CodePudding user response:

std::sort uses std::less as default comparator. For a std::pair that just calls the elements operator< and sorts with respect to first, then second. For details see here: https://en.cppreference.com/w/cpp/utility/pair/operator_cmp.

However, comparing pointers that are not pointing to elements of the same array via < is implementation defined. You need to use std::less for proper comparison of pointers in general.

Hence, the order of elements with same first is implementation defined and difficult to be reproduced exactly.

CodePudding user response:

sort(A.begin(), A.end(), 
[]( pair<int, myClass *> p1, pair<int, myClass *>p2 )  
{ return p1.first < p2.first; });

modify the lambda according your wish or how you want the sorting to happen.

  • Related