简体   繁体   English

对包含类的“ std :: vector”进行排序

[英]sort the 'std::vector' containing classes

Sort by using a binary predicate and std::sort 通过使用二进制谓词和std::sort

I need the sample for this... 我需要样品...

Here is another adaptation of the example that uses two different kinds of predicates. 这是使用两种不同谓词的示例的另一种改编。 The predicate specified can be a function pointer or a functor which is a class that defines operator() so that the object when instantiated can be used just like a function would be. 指定的谓词可以是函数指针或函子,函子是定义operator()的类,以便实例化对象时可以像使用函数一样使用。 Notice that I had to add one more header inclusion to the functional header. 注意,我必须在功能头中再添加一个头包含。 This is because the functor inherits from binary_function which is defined within the std library. 这是因为函子继承自std库中定义的binary_function。

 #include <iostream>
 #include <vector>
 #include <algorithm>
 #include <functional>

 using namespace std;

 class MyData
 {
  public:
    static bool compareMyDataPredicate(MyData lhs, MyData rhs) { return (lhs.m_iData <                        rhs.m_iData); }
    // declare the functor nested within MyData.
      struct compareMyDataFunctor : public binary_function<MyData, MyData, bool>
   {
      bool operator()( MyData lhs, MyData rhs)
        {
            return (lhs.m_iData < rhs.m_iData);
         }
    };

   int m_iData;
      string m_strSomeOtherData;
   };


 int main()
{
  // Create a vector that contents elements of type MyData
     vector<MyData> myvector;

       // Add data to the vector
        MyData data;
       for(unsigned int i = 0; i < 10; ++i)
       {
          data.m_iData = i;
          myvector.push_back(data);
       }

    // shuffle the elements randomly
       std::random_shuffle(myvector.begin(), myvector.end());

       // Sort the vector using predicate and std::sort.  In this case the predicate is     a static
       // member function.
      std::sort(myvector.begin(), myvector.end(), MyData::compareMyDataPredicate);

      // Dump the vector to check the result
    for (vector<MyData>::const_iterator citer = myvector.begin();
        citer != myvector.end(); ++citer)
   {
        cout << (*citer).m_iData << endl;
     }

   // Now shuffle and sort using a functor.  It has the same effect but is just a different
       // way of doing it which is more object oriented.
         std::random_shuffle(myvector.begin(), myvector.end());

       // Sort the vector using predicate and std::sort.  In this case the predicate is a functor.
         // the functor is a type of struct so you have to call its constructor as the third argument.
       std::sort(myvector.begin(), myvector.end(), MyData::compareMyDataFunctor());

    // Dump the vector to check the result
        for (vector<MyData>::const_iterator citer = myvector.begin();
        citer != myvector.end(); ++citer)
    {     
           cout << (*citer).m_iData << endl;
      }
    return 1;
   }
// alg_sort.cpp
// compile with: /EHsc
#include <vector>
#include <algorithm>
#include <functional>      // For greater<int>( )
#include <iostream>

// Return whether first element is greater than the second
bool UDgreater ( int elem1, int elem2 )
{
   return elem1 > elem2;
}

int main( )
{
   using namespace std;
   vector <int> v1;
   vector <int>::iterator Iter1;

   int i;
   for ( i = 0 ; i <= 5 ; i++ )
   {
      v1.push_back( 2 * i );
   }

   int ii;
   for ( ii = 0 ; ii <= 5 ; ii++ )
   {
      v1.push_back( 2 * ii + 1 );
   }

   cout << "Original vector v1 = ( " ;
   for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
      cout << *Iter1 << " ";
   cout << ")" << endl;

   sort( v1.begin( ), v1.end( ) );
   cout << "Sorted vector v1 = ( " ;
   for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
      cout << *Iter1 << " ";
   cout << ")" << endl;

   // To sort in descending order. specify binary predicate
   sort( v1.begin( ), v1.end( ), greater<int>( ) );
   cout << "Resorted (greater) vector v1 = ( " ;
   for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
      cout << *Iter1 << " ";
   cout << ")" << endl;

   // A user-defined (UD) binary predicate can also be used
   sort( v1.begin( ), v1.end( ), UDgreater );
   cout << "Resorted (UDgreater) vector v1 = ( " ;
   for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
      cout << *Iter1 << " ";
   cout << ")" << endl;
}
std::sort(v.begin(), v.end(), predicate);

where predicate is a function with the following property: 其中predicate是具有以下属性的函数:

User-defined predicate function object that defines the comparison criterion to be satisfied by successive elements in the ordering. 用户定义的谓词功能对象,该对象定义排序条件中连续元素要满足的比较标准。 A binary predicate takes two arguments and returns true when satisfied and false when not satisfied. 二进制谓词带有两个参数,如果满足则返回true ,不满足则返回false This comparator function must impose a strict weak ordering on pairs of elements from the sequence. 该比较器功能必须对序列中的成对元素施加严格的弱排序。

( MSDN ) MSDN

Eg: 例如:

bool strings_lt_by_first_char(std::string const &x, std::string const &y)
{
    return x[0] < y[0];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM