Sorting with operator<

Lab C++ Intermediate 20 points

Write struct Card { int rank; char suit; } with operator< (by rank, then suit). Read cards like 10H, 2S, sort them with plain sort(begin, end) and print them.

Input

n, then n cards (rank 2-14, suit C D H S).

Output

One line.

Example

Input

5
10H
2S
14C
10D
2C

Output

2C 2S 10D 10H 14C
Sample input available Sample output available
Editor
C++

Hints

sort uses operator< when no comparator is given (fine for your own types).

Solution explanation

Defining < gives your type a natural order usable by sort, set and map.

Show solution
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

struct Card {
    int rank;
    char suit;
    bool operator<(const Card &o) const {
        if (rank != o.rank) return rank < o.rank;
        return suit < o.suit;
    }
};

int main() {
    int n;
    cin >> n;
    vector<Card> cards(n);
    for (auto &c : cards) {
        string s;
        cin >> s;
        c.suit = s.back();
        c.rank = stoi(s.substr(0, s.size() - 1));
    }
    sort(cards.begin(), cards.end());
    for (size_t i = 0; i < cards.size(); i++) {
        cout << cards[i].rank << cards[i].suit << (i + 1 < cards.size() ? " " : "\n");
    }
    return 0;
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD