Sorting a vector of custom objects

后端 未结 13 2983
既然无缘
既然无缘 2020-11-21 05:14

How does one go about sorting a vector containing custom (i.e. user defined) objects.
Probably, standard STL algorithm sort along with a predicate (a fu

13条回答
  •  不思量自难忘°
    2020-11-21 05:33

    A simple example using std::sort

    struct MyStruct
    {
        int key;
        std::string stringValue;
    
        MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
    };
    
    struct less_than_key
    {
        inline bool operator() (const MyStruct& struct1, const MyStruct& struct2)
        {
            return (struct1.key < struct2.key);
        }
    };
    
    std::vector < MyStruct > vec;
    
    vec.push_back(MyStruct(4, "test"));
    vec.push_back(MyStruct(3, "a"));
    vec.push_back(MyStruct(2, "is"));
    vec.push_back(MyStruct(1, "this"));
    
    std::sort(vec.begin(), vec.end(), less_than_key());
    

    Edit: As Kirill V. Lyadvinsky pointed out, instead of supplying a sort predicate, you can implement the operator< for MyStruct:

    struct MyStruct
    {
        int key;
        std::string stringValue;
    
        MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
    
        bool operator < (const MyStruct& str) const
        {
            return (key < str.key);
        }
    };
    

    Using this method means you can simply sort the vector as follows:

    std::sort(vec.begin(), vec.end());
    

    Edit2: As Kappa suggests you can also sort the vector in the descending order by overloading a > operator and changing call of sort a bit:

    struct MyStruct
    {
        int key;
        std::string stringValue;
    
        MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
    
        bool operator > (const MyStruct& str) const
        {
            return (key > str.key);
        }
    };
    

    And you should call sort as:

    std::sort(vec.begin(), vec.end(),greater());
    

提交回复
热议问题