Mr.Curiosity
Mr.Curiosity

Reputation: 69

Sort the list alphabetically in descending order and print the list

a. Store 5 names in a list. Allow the user to input each name.
b. Sort the list alphabetically in ascending order and print the list. c. Sort the list alphabetically in descending order and print the list.
d. Ensure your code can be executed without bugs or errors.

im stuck in sorting the list in descending order please help:(

below is my source code of the ascending order.

#include <iostream>
#include <set>
#include <algorithm>

void print(const std::string& item)
{
    std::cout << item << std::endl;
}

int main()
{
    std::set<std::string> sortedItems;

    for(int i = 1; i <= 5; ++i)
    {
        std::string name;
        std::cout << i << ". ";
        std::cin >> name;

        sortedItems.insert(name);
    }

    std::for_each(sortedItems.begin(), sortedItems.end(), &print);
    return 0;
}

Upvotes: 0

Views: 3634

Answers (2)

Jarod42
Jarod42

Reputation: 217265

To display the set in reverse order, you may use:

std::for_each(sortedItems.rbegin(), sortedItems.rend(), &print);

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

To sort a list, you don't need std::set, you can store the names in a std::vector and then use the function std::sort from the header algorithm. There is also a version of the function that takes a predicate and thus you can reverse the order using this predicate, specifying reverse comparison. Have a look at the documentation of sort. Also have a look at greater that is defined in the header functional - this is a predicate you can use to reverse the sorting order. Have a look at this short example on ideone:

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

int main() {
    vector<string> test;
    test.push_back("a");
    test.push_back("c");
    test.push_back("b");
    sort(test.begin(), test.end());
    for (unsigned i = 0; i < test.size(); ++i) {
        cout << test[i] << endl;
    }
    sort(test.begin(), test.end(), greater<string>());
    for (unsigned i = 0; i < test.size(); ++i) {
        cout << test[i] << endl;
    }
    return 0;
}

Upvotes: 2

Related Questions