如何对包含自定义(即用户定义的)对象的向量进行排序。 可能,应该使用标准的STL算法排序以及一个谓词(函数或函数对象),该谓词将对自定义对象中的一个字段(作为排序的键)进行操作。 我的思路对吗?


当前回答

在类中,可以重载"<"操作符。

class MyClass
{
  bool operator <(const MyClass& rhs)
  {
    return this->key < rhs.key;
  }
}

其他回答

中使用sort()算法对向量进行排序。

sort(vec.begin(),vec.end(),less<int>());

使用的第三个参数可以是更大或更小,也可以使用任何函数或对象。但是,如果第三个参数为空,则默认操作符为<。

// using function as comp
std::sort (myvector.begin()+4, myvector.end(), myfunction);
bool myfunction (int i,int j) { return (i<j); }

// using object as comp
std::sort (myvector.begin(), myvector.end(), myobject);

你的思路是对的。Std::sort默认使用操作符<作为比较函数。所以为了对对象排序,你要么重载bool操作符<(const T&, const T&),要么提供一个函数对象来进行比较,就像这样:

 struct C {
    int i;
    static bool before( const C& c1, const C& c2 ) { return c1.i < c2.i; }
 };

 bool operator<( const C& c1, const C& c2 ) { return c1.i > c2.i; }

 std::vector<C> values;

 std::sort( values.begin(), values.end() ); // uses operator<
 std::sort( values.begin(), values.end(), C::before );

使用函数对象的好处是可以使用函数访问类的私有成员。

您可以使用用户定义的比较器类。

class comparator
{
    int x;
    bool operator()( const comparator &m,  const comparator &n )
    { 
       return m.x<n.x;
    }
 }
    // sort algorithm example
    #include <iostream>     // std::cout
    #include <algorithm>    // std::sort
    #include <vector>       // std::vector
    using namespace std;
    int main () {
        char myints[] = {'F','C','E','G','A','H','B','D'};
        vector<char> myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33
        // using default comparison (operator <):
        sort (myvector.begin(), myvector.end());           //(12 32 45 71)26 80 53 33
        // print out content:
        cout << "myvector contains:";
        for (int i=0; i!=8; i++)
            cout << ' ' <<myvector[i];
        cout << '\n';
        system("PAUSE");
    return 0;
    }

是的,std::sort()与第三个参数(函数或对象)将更容易。一个例子: http://www.cplusplus.com/reference/algorithm/sort/