using stl list?

I'm trying to sort a list of structs. I'm not very familiar with the stl list.
Could anyone explain the sort function and how it operates?
The Program:
I read in from a file into a map. Then I transfer the information from the map into a linked list of structs. All of that works properly. I need to sort the list according to the int count and then display. Any suggestions would be appreciated. It is not required that I use a linked list, I just thought it might be easier.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <map>
#include <string>
#include <fstream>
#include <list>
using namespace std;

struct Data
{
	string key;
	int count;
};


list<Data> listOfData;
Last edited on
I'm not too sure how sorting a non-primitive list would go. Here is the link:
http://www.cplusplus.com/reference/stl/list/sort/

Maybe it is as simple as:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool compare(Data first, Data second)
{
 if (first.count > second.count) return true;
 return false;
}

int main()
{
  list<Data> dataList;
  
  // do things

  dataList.sort(compare); 

}



Maybe??
Last edited on
You can do something like that, but it is likely easier to just define bool operator<(), like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct foo
{
	int a;
	bool operator<(const foo & rhs)
	{
		return a < rhs.a;
	}
};

int main()
{
	list<foo> mylist;
	mylist.sort();
	return 0;
}
Thanks.
@ rollie: worked like a charm :)
Topic archived. No new replies allowed.