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:
- obj3 //(1,5)
- obj2 //(2,4)
- obj1 //(2,5)
- 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?
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]);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With