Search code examples
c++qtsortingc++11mixed

How safe it is to sort a mixed datatype vector based on the integer value included in datatype using std::sort?


I wrote the following code in Qt creator. I was trying to sort a vector that contains mixed type with 2 QStrings and an integer. I used std::sort and its function mechanism to sort. At least in the output pre-sorting and post-sorting, it seems the sorting worked, but my question is, accurate and safe could it be?

Thanks.

#include <vector>
#include <algorithm>
#include <QDebug>

class mixed
{
public:
    int number;
    QString name;
    QString address;
    mixed(int n, QString s, QString a)
    {
        number = n;
        name = s;
        address = a;
    }

};

bool myfunction (mixed i,mixed j) { return (i.number<j.number); }

int main()
{
    std::vector<mixed>myV;
    myV.push_back(mixed(100, "akkas", "100"));
    myV.push_back(mixed(2, "akkas1", "2"));
    myV.push_back(mixed(1111, "akkas2", "1111"));
    myV.push_back(mixed(-1, "akkas3", "-1"));
    myV.push_back(mixed(7, "akkas4", "7"));
    myV.push_back(mixed(0, "akkas0", "0"));

    for(int i=0; i<myV.size(); i++)
    {
        qDebug()<<myV.at(i).number<<" "<<myV.at(i).name<<" "<<myV.at(i).address<<endl;
    }
    std::sort (myV.begin(), myV.end(), myfunction);

    for(int i=0; i<myV.size(); i++)
    {
        qDebug()<<myV.at(i).number<<" "<<myV.at(i).name<<" "<<myV.at(i).address<<endl;
    }

    return 0;
}

Solution

  • std::sort can sort elements of any type so long as they're either copyable or movable. The comparison function provided must induce a strict weak ordering. Your comparison function is a valid strict weak ordering, which lumps all objects with equal number into a single equivalence class. If the unsorted vector contains records with equal number values, they will be adjacent in the sorted vector, but the order is unspecified.