Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting vector of objects by object's variable

I have a vector of objects. Each of these objects has 2 fields (the values of which can be repeated), e.g:

//myClass name = myClass(x,y)
myClass obj1 = myClass(2,5);
myClass obj2 = myClass(2,4);
myClass obj3 = myClass(1,5);
myClass obj4 = myClass(3,2);
 
std::vector<myClass> myVector;
 
myVector.push_back(obj1);
myVector.push_back(obj2);
myVector.push_back(obj3);
myVector.push_back(obj4);

I want to sort the vector. First it should be sorted by 1st values. If the values of the 1st variable is the same, then should be sorted by second variable. Vector after sorting should be like that:

  1. obj3 //(1,5)
  2. obj2 //(2,4)
  3. obj1 //(2,5)
  4. obj4 //(3,2)

I have wrote this simple code with bubble sort:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for (int i = 0; i < myVector.size(); i++)
    {
        for (int j = 0; j < myVector.size() - 1; j++)
        {
            if (myVector[j].x < myVector[j + 1].x)
                std::swap(myVector[j], myVector[j + 1]);
        }
    }

Now myVector is sorted by first value, but how to sort elements, which first value it the same, by second value? Like in example?

>Solution :

You may change your if statement to:

if ( (myVector[j].x == myVector[j + 1].x) ? (myVector[j].y < myVector[j + 1].y) : (myVector[j].x < myVector[j + 1].x)  ) 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading