Sorting a vector of structs

I've been searching Google for a while looking for a solution, but none of them seem to work and I'm over my head trying to figure this last part out.

I have a struct:


struct Node{
	public:
		string word;	  
		int count;
	Node(string s, int c){
		word = s;
		count = c;
	}		
};


and I have a vector of these structs:

vector <Node *> nodes;


which I have filled with the structs containing words from a document and then for every time a word is repeated I increment the count.

I now need to print out the top 10 repeated words so I need to sort my vector by the count value of my structs.

This is what I've come up with so far from my Google searching, but it's throwing me all sorts of errors that I believe have to do with the pointers I'm using. I need to include these pointers for my class though.

sort( nodes.begin(), nodes.end()); 


I know the sort is wrong because it sorts the structs and not the count value, how would I go about sorting the structs by the count value?
http://www.cplusplus.com/reference/algorithm/sort/


Check out the comparison function.

Hope all goes well.
Yes I've been trying to figure that page out with no luck. I'm interested in the using object as comp solution, but am not able to implement it in my own program - probably for lack of knowledge/howto.

Thanks though
So what does you code look like now?

The article showed having a bool operator() do you have one of those?
1
2
3
4
5
6
7
8
9
10
11
12
struct Node{
	public:
		string word;	  
		int count;
	Node(string s, int c){
		word = s;
		count = c;
	}	
        bool operator()(Node*& first, Node*& second){
                return first->count > second->count;
        }	
};


Which I believe works just fine. What I don't understand is the 'myobject' that is required in the sort using object as comp.
I apologise if this sound silly, but have you created an object of type Node and used in the call to sort?

In the documentation, it has myobject as a myclass struct type

HTH
Last edited on
I tried that, but it didn't work for some reason having to do with it being a vector of pointers. I just figured out another way to do it though. It works, but I'm sure it's not the best way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct Node{
	public:
		string word;	  
		int count;
	Node(string s, int c){
		word = s;
		count = c;
	}		
};

struct Sort
{
     bool operator()(Node*& first, Node*& second)
     {
          return first->count > second->count;
     }
};


 
sort (nodes.begin(), nodes.end(),Sort()); 
Topic archived. No new replies allowed.