-4

I have a vector of object pointers, and now I want to sort them according to their char keys. To be more specific, I want to sort the char keys (char c) in "lexicographical order".

For example, suppose I have a vector of objects of POINTERS<o1, o2, o3, o4, o5>, and: o1->c = 'd'; o2->c = 'k'; o3->c = 'x'; o4->c = 'a'; o5->c = 'j' then after sorting, the vector should be: <o4, o1, o5, o2, o3>

How do I do that? Thank you.

Einsambr
  • 189
  • 2
  • 11
  • 3
    Try looking it up here: [the first result when googling "c++ sort vector"](http://www.cplusplus.com/reference/algorithm/sort/). – riodoro1 Jun 01 '17 at 08:59
  • actually what I am asking is sorting object POINTERS (I didn't mention that in the original question)...... would that be the same as sorting objects? – Einsambr Jun 01 '17 at 09:12

1 Answers1

0

std::sort allows you to pass a custom predicate to it:

std::vector<Object*> objects = ...;
std::sort(objects.begin(), 
          objects.end(), 
          [](Object const * x, Object const * y) { return x->c < y->c; });

If you have an older compiler that cannot use lambdas, you have to create a class that implements the comparison:

struct Foo
{
  bool operator()(Object const * x, Object const * y) const
  {
    return x->c < y->c;
  }
};

std::sort(objects.begin(), objects.end(), Foo());
MadScientist
  • 3,390
  • 15
  • 19