Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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?

like image 874
Mavimix Avatar asked Nov 28 '25 02:11

Mavimix


1 Answers

You can try something like that:

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]);
            }
            else if (myVector[j].x == myVector[j + 1].x)
            {
                if (myVector[j].y < myVector[j + 1].y)
                    std::swap(myVector[j], myVector[j + 1]);
            }
        }
    }
like image 72
Yannis Sauzeau Avatar answered Nov 29 '25 21:11

Yannis Sauzeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!