STL Sorting: How to sort a 'std::vector' containing classes/structures?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: STL Sorting: How to sort a 'std::vector' containing classes/structures?

Threaded View

  1. #1
    Join Date
    Nov 2003
    Location
    Belgium
    Posts
    8,062

    STL Sorting: How to sort a 'std::vector' containing classes/structures?

    Q: How to sort a 'std::vector' containing classes/structures?

    A:
    • Sort by using a binary predicate and 'std::sort':

      Code:
      #include <vector>
      #include <string>
      #include <iostream>
      #include <algorithm>
      
      using namespace std;
      
      class MyData
      {
      public:
        int m_iData;
        string m_strSomeOtherData;
      };
      
      bool MyDataSortPredicate(const MyData& d1, const MyData& d2)
      {
        return d1.m_iData < d2.m_iData;
      }
       
      int main()
      {
        // Create a vector that contains elements of type MyData
        vector<MyData> myvector;
      
        // Add data to the vector
        MyData data;
        data.m_iData = 3;
        myvector.push_back(data);
      
        data.m_iData = 1;
        myvector.push_back(data);
      
        // Sort the vector using predicate and std::sort
        std::sort(myvector.begin(), myvector.end(), MyDataSortPredicate);
      
        // 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;
      }
    Last edited by Marc G; June 6th, 2009 at 01:43 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center