473,322 Members | 1,417 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

sort more than one variable in STL

Hi there,

Does STL provide some function to sort several variables together by
one of them? Say I have 100 student's names, age and scores, and I
want to sort them by score only.

I know I can modify the quicksort code, but just want something quick
and neat.

Thank you for your help.

jack
Jul 22 '05 #1
3 1146
jack wrote in news:1c**************************@posting.google.c om in
comp.lang.c++:
Hi there,

Does STL provide some function to sort several variables together by
one of them? Say I have 100 student's names, age and scores, and I
want to sort them by score only.

I know I can modify the quicksort code, but just want something quick
and neat.

Thank you for your help.


Yes std::sort() can take an optional "Functor" argument, a simple
function that returns true if the `left` is less than the `right`
will do:

#include <string>
#include <vector>
#include <algorithm>

struct student_t
{
std::string name;
int age, score;
};

bool by_score( student_t const &lhs, student_t const &rhs )
{
return lhs.score < rhs.score;
}

int main()
{
std::vector< student_t > students;
// populate students

std::sort( students.begin(), students.end(), by_score );
}

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #2

"jack" <id***@yahoo.com> wrote in message news:1c**************************@posting.google.c om...
Hi there,

Does STL provide some function to sort several variables together by
one of them? Say I have 100 student's names, age and scores, and I
want to sort them by score only.

I know I can modify the quicksort code, but just want something quick
and neat.

Thank you for your help.

jack


You could use a multimap. Something like the following should work for you.
I've used this kind of scheme before to solve this kind of issue:

#include <iostream>
#include <map>
#include <utility>
#include <string>

struct StudentData
{
std::string name;
int age;
int score;
};

int main(void)
{
std::multimap<int, StudentData> StudentMap;
StudentData temp;

temp.name = "Ralph";
temp.age = 7;
temp.score = 86;
StudentMap.insert(std::make_pair(temp.score, temp));

temp.name = "Tom";
temp.age = 9;
temp.score = 52;
StudentMap.insert(std::make_pair(temp.score, temp));

temp.name = "Susan";
temp.age = 8;
temp.score = 94;
StudentMap.insert(std::make_pair(temp.score, temp));

temp.name = "Fred";
temp.age = 10;
temp.score = 86;
StudentMap.insert(std::make_pair(temp.score, temp));

// The above will automatically sort students by score.
// Use lower_bound(), upper_bound(), and equal_range() to get
// iterators to students with particular scores. For example, the
// following will print all the students who scored each possible score
// from 0 to 100:

typedef std::multimap<int, StudentData>::iterator SMI;
std::pair<SMI, SMI> Range;
for (int score = 0; score<=100; ++score)
{
Range = StudentMap.equal_range(score);
if (Range.first == Range.second) continue;
std::cout << "Students with score " << score << ":" << std::endl;
for (SMI iter = Range.first; iter != Range.second; ++iter)
{
std::cout << (*iter).second.name << std::endl;
}
}
}

--
Cheers,
Robbie Hatley
Tustin, CA, USA
email: lonewolfintj at pacbell dot net
web: home dot pacbell dot net slant earnur slant


----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Jul 22 '05 #3
Does STL provide some function to sort several variables together by
one of them? Say I have 100 student's names, age and scores, and I
want to sort them by score only.


I am not sure if I do understand what you want to do...

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>

using namespace std;
class student
{
friend ostream &operator<<(ostream &o, const student &e);
private:
int score;
int age;
char *name;
public:
student (int s) : score (s) {}
int get_score () const { return score;}
bool operator<(const student &e) const { return score < e.score; }
};

ostream &operator<<(ostream &o, const student &e)
{
return o << e.score;
}

int
main ()
{
vector<student> v;
for (int i = 0; i < 20 ; i++)
v.push_back (student (i));

// add some noise
random_shuffle (v.begin(), v.end());
ostream_iterator<student> outp (cout, " ");
cout << "student scores before sorting: " << endl;
copy (v.begin(), v.end(), outp);
cout << endl;
cout << "now we sort: " << endl;
sort (v.begin(), v.end());
copy (v.begin(), v.end(), outp);
cout << endl;

return 0;
}

Jul 22 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Diego Barros | last post by:
Hello, I was wondering if it was posibble to sort a map using the values and not the keys. Sorting on the keys (if they were strings, for example) is currently possible. What about, for example,...
7
by: Christopher Jeris | last post by:
I am relatively new to JavaScript, though not to programming, and I'm having trouble finding the idiomatic JS solution to the following problem. I have a table with (say) fields f1, f2, f3. I...
40
by: Elijah Bailey | last post by:
I want to sort a set of records using STL's sort() function, but dont see an easy way to do it. I have a char *data; which has size mn bytes where m is size of the record and n is the...
20
by: Xah Lee | last post by:
Sort a List Xah Lee, 200510 In this page, we show how to sort a list in Python & Perl and also discuss some math of sort. To sort a list in Python, use the “sort†method. For example: ...
25
by: Rainmaker | last post by:
Hi, Can anyone tell me an efficient algorithm to sort an array of strings? Keep in mind that this array is HUGE and so the algorithm should me efficient enough to deal with it. Thanks
2
by: jobooker | last post by:
I'm having issues sorting. The short description is, how do I set the select attribute of xsl:sort to be the value of an xsl:variable? The longer description follows: What I want to do is to be...
15
by: bcochofel | last post by:
Hi, I want to use a variable to sort elements. That var his passed with query string (I'm using Perl CGI to generate XML). Here's a sample of my output:...
7
by: ^cypis^ vel. SQ9JTI | last post by:
Hi, i need your help. I have to prepare a homework, easy program, which will be sorting the values from txt file and writing the solution to another txt file. It has to be a bucket sort. Have...
12
by: Cindy Lee | last post by:
When I do a sorta on 1 table, then the other table goes back to the original order. What can I set so, it keeps the order of the other current gridview's order. I set all the gridview values...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.