c++ - 对包含类的 'std::vector' 进行排序

标签 c++ visual-c++

使用二进制谓词和 std::sort 进行排序

我需要这个 sample ...

最佳答案

这是使用两种不同类型谓词的示例的另一种改编。指定的谓词可以是函数指针或仿函数,仿函数是定义 operator() 的类,以便对象在实例化时可以像函数一样使用。请注意,我必须向功能 header 添加一个 header 包含。这是因为仿函数继承自 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;
   }

关于c++ - 对包含类的 'std::vector' 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5468194/

相关文章:

visual-c++ - 是否可以将 boost::serialization 与托管类一起使用?

c++ - 什么是 isWindowsServer API for VS 2008 编译器的等价物

c++ - 是否可以为基于对话框的窗口而不是框架窗口创建 MDI 窗口?

c++ - 将 std vector 重新分配给默认构造函数 vector 是删除的好方法吗?

c++ - 如何将 dynamic_cast 与 for_each 一起使用

visual-c++ - 初始化 GUID 变量

c - Loadlibrary 总是返回 NULL

.net - 如何重新分发 .Net Framework

c++ - 用它的索引范围打包元组

c++ - 旋转二叉树