开发者

How can I sort the vector elements using members as the key in C++

suppose we have a

vector<student> allstudent

Now I would like to sort the students using dif开发者_如何学Goferent memebers,such as name, age, address, like that.

How can I do that?


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());

Starting with C++11, you can use a lambda expression to do the comparison "in place", something like this:

// sort by name:
std::sort(students.begin(), students.end(), 
    [](student const &a, student const &b) {
        return a.name < b.name; 
    });

// sort by age:
std::sort(students.begin(), students.end(), 
    [](student const &a, student const &b) {
        return a.age < b.age; 
    });


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



std::sort(students.begin(), students.end(),
  [](student const& stud1, student const& stud2) -> bool
  {
    return stud1.name() < stud2.name();
  });

Or if you don't have access to a compiler with lambda statements:


std::sort(students.begin(), students.end(),
          boost::bind(&student::name, _1) < boost::bind(&student::name _2));

Or do it Coffin's way. I tended to avoid the standard algorithms when you had to do it like that though...I'm lazy.


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.


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜