0

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;
}
Mr.Curiosity
  • 69
  • 2
  • 4
  • There are plenty of questions on sorting stuff in C++ out there. For example, http://stackoverflow.com/questions/1380463/sorting-a-vector-of-custom-objects – juanchopanza Oct 15 '14 at 06:07
  • I predict that you're going to fail this exercise unless you actually follow the instructions: *first* store the names in a list, *then* sort the list. You've done neither. The result isn't what's important, it's the process. – molbdnilo Oct 15 '14 at 06:27
  • Don't forget to credit this web site when you turn in your assignment, since you got outside assistance. Check your school's academic honesty policy. – Raymond Chen Oct 15 '14 at 08:11

2 Answers2

2

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;
}
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
1

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

std::for_each(sortedItems.rbegin(), sortedItems.rend(), &print);
Jarod42
  • 203,559
  • 14
  • 181
  • 302