468,512 Members | 1,423 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,512 developers. It's quick & easy.

Sorting a vector of structs

5
Hi there,

I have struct like this one:

Expand|Select|Wrap|Line Numbers
  1. struct kurs
  2. {
  3.         unsigned short int var1;
  4.         string string_var;
  5.         int sort_var;
  6. };
// and a vector like this one
Expand|Select|Wrap|Line Numbers
  1. vector < struct kurs> kurs_2;

thing is that I want to sort a vector by sort_var.
How can I do that?

Regards,
Philia
Dec 9 '07 #1
2 3148
Laharl
849 Expert 512MB
You can overload operator< to return based on that value, or write a function that takes two kurs inputs and returns one < other based on that variable. Then, you can call sort() from #algorithm and bingo, it's sorted. Note that using the second option requires using the three-parameter sort with the function name as the third argument.
Dec 9 '07 #2
Philia
5
Thank you for reply.

I made it this way:
Expand|Select|Wrap|Line Numbers
  1. class sorting
  2. {
  3.  
  4. public:
  5.  
  6.     bool operator() ( const kurs & s, const kurs & t)
  7.  
  8.     {
  9.  
  10.         return s.wspolczynnik_sort < t.wspolczynnik_sort;
  11.  
  12.     }
  13.  
  14. };
...
Expand|Select|Wrap|Line Numbers
  1. std::sort(kursy_2.begin(),kursy_2.end(),sorting());
Hope it will be helpful to someone :)

Regards,
Philia
Dec 9 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

reply views Thread by Alex Vinokur | last post: by
5 posts views Thread by RocTheEngy | last post: by
8 posts views Thread by Joe Van Dyk | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.