views:

142

answers:

5

suppose we have a

vector<student> allstudent

Now I would like to sort the students using different memebers,such as name, age, address, like that.

How can I do that?

+21  A: 

Create a functor to compare the correct field, then specify the functor when you sort:

struct by_age { 
    bool operator()(student const &a, student const &b) const { 
        return a.age < b.age;
    }
};

struct by_name { 
    bool operator()(student const &a, student const &b) const { 
        return a.name < b.name;
    }
};

// sort by age
std::sort(students.begin(), students.end(), by_age());

// sort by name
std::sort(students.begin(), students.end(), by_name());
Jerry Coffin
Make those operators `const`. :P
GMan
Are the () after by_age and by_name in the std::sort calls supposed to be there?
Dan
@GMan: Oops -- thank you. Fixed. @Dan: Yes -- without the parens, we'd be passing the name of a class, which won't work. With the parens, we're passing an instance of the class, which will.
Jerry Coffin
+5  A: 

These are two easy ways:

bool operator <(const student &lhs, const student &rhs)
{
    return lhs.age < rhs.age;
}

std::sort(allstudent.begin(), allstudent.end()); // sorts by age

Or write a compare function:

bool cmp(const student &lhs, const student &rhs)
{
    return lhs.age < rhs.age; // here go your sort conditions
}

std::sort(allstudent.begin(), allstudent.end(), cmp); // also sorts by age
IVlad
+5  A: 
Noah Roberts
hahahaaaaa, c++0x. love it
ianmac45
A: 

in general, boost::multi_index provides a lot of this functionality. This comes in especially useful if you need rapid access on more than one key. This answer won't help you with your homework though ;-) See http://www.boost.org/

bert hubert
bloated and doesn't help with his homework.
Jay
+2  A: 

In addition to earlier comments, you can also define multidimensional filters, like this:

bool operator <(const student &a, const student &b)
{
    return ((a.age < b.age) ||
            ((a.name < b.name) && (a.age == b.age)) ||
            ((a.address <= b.address) && (a.name == b.name) && (a.age == b.age)))
}

Just like the operator above, you can make more advanced filters if needed.

Lajos Arpad