-
November 24th, 2005, 10:04 AM
#1
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 12: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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|