array sorting

For everyone, just starting with C++ or programming at all. Ask newbie questions in this forum!

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

array sorting

Postby tomerhamam » Mon Apr 02, 2012 4:38 am

Hi,
I wonder if there is a function that can sort one column of array according to other column in the array.
e.g. first columns contains names, the second column contains a score for each name, and I want to sort the names according to their grades?
Thanks
Tomer
tomerhamam
 
Posts: 1
Joined: Mon Apr 02, 2012 4:36 am

Re: array sorting

Postby exomo » Mon Apr 02, 2012 1:22 pm

Arrays have only members of the same datatype, you can't mix strings and numbers.

You can define a structure
Code: Select all
struct foo
{
    string name;
    int score;
};

and define an array of this structure. Then you can sort the array. You have to define a compare operator or a compare function or a functor class.
Code: Select all
bool operator<(foo &a, foo &b)
{
    return a.score < b.score;
}

If you use std::vector instead of an array the sorting is as easy as
Code: Select all
std::vector<foo> foovector;
// put some elements in the vector
std::sort(foovector.begin(), foovector.end());
Who needs a signature anyway.
User avatar
exomo
 
Posts: 879
Joined: Fri Sep 26, 2003 12:30 pm
Location: germany->baden


Return to For Beginners

Who is online

Users browsing this forum: No registered users and 3 guests