-
November 24th, 2005, 10:03 AM
#1
STL Sorting: How to sort a 'std::list' containing classes/structures?
Q: How to sort a 'std::list' containing classes/structures?
A: There are 2 ways to sort such a list:
- Overriding the < operator
Code:
#include <list>
#include <string>
#include <iostream>
using namespace std;
class MyData
{
public:
int m_iData;
string m_strSomeOtherData;
bool operator < (const MyData& rhs)
{
return m_iData < rhs.m_iData;
}
};
int main()
{
// Create list
list<MyData> mylist;
// Add data to the list
MyData data;
data.m_iData = 3;
mylist.push_back(data);
data.m_iData = 1;
mylist.push_back(data);
// Sort the list
mylist.sort();
// Dump the list to check the result
for (list<MyData>::const_iterator citer = mylist.begin();
citer != mylist.end(); ++citer)
{
cout << (*citer).m_iData << endl;
}
return 1;
}
- Using a binary predicate
Code:
#include <list>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
class MyData
{
public:
int m_iData;
string m_strSomeOtherData;
};
bool MyDataSortPredicate(const MyData& lhs, const MyData& rhs)
{
return lhs.m_iData < rhs.m_iData;
}
int main()
{
// Create list
list<MyData> mylist;
// Add data to the list
MyData data;
data.m_iData = 3;
mylist.push_back(data);
data.m_iData = 1;
mylist.push_back(data);
// Sort the list using predicate
mylist.sort(MyDataSortPredicate);
// Dump the list to check the result
for (list<MyData>::const_iterator citer = mylist.begin();
citer != mylist.end(); ++citer)
{
cout << (*citer).m_iData << endl;
}
return 1;
}
Note: 'std::sort' cannot be used to sort 'std::list' because it requires a random access iterator which is not available for a list.
Last edited by Marc G; February 2nd, 2008 at 03:43 AM.
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
|