0

I have a vector container holding some objects. The objects have various attributes, primarily ints and strings. I want an STL algorithm for sorting the container by its different attributes. For example, if a collection of baseball cards has a player name which is a string, and a year the player started baseball, which is an integer, how can I sort the vector container by year number and then later sort it alphabetically by player name? I never really learned STL because my professors forbade its use in the past, so I'm trying to learn it now so I can program more quickly.

John4562
  • 11
  • 3

2 Answers2

2

The std::sort() function uses a binary predicate as third argument which can be used to customize the sort order. You can just use two different predicates:

 std::sort(v.begin() v.end(),
    [](card const& c0, card const& c1){
        return c0.name() < c1.name();
    });

... and likewise for other attributes.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
1

All you need to do is

#include <algorithm>

bool operator<(const MyObject& x, const MyObject& y)
{
    ...
}

std::sort(vec.begin(), vec.end());

Use operator< to define the order you want, it returns true if x should be before y after sorting and false otherwise. From your description is sounds like you want to compare years first, and if they are equal then compare names.

Shame about your professors.

john
  • 85,011
  • 4
  • 57
  • 81
  • No, I don't really care about partial orderings in the middle. I just want to sort by name, display to the screen, and then sort by year, and display to the screen. – John4562 Sep 01 '13 at 16:45