0

I have a list of strings that contains words like: Amount, bird, ant, Bob, David, case... I need to sort them in dictionary order (Amount, ant, bird, Bob, case, David...)

I use the insertion sort which turned out the output to be all capital letters in front and then lower case strings (Amount, Bob, David, ant, bird, case...).

my question is what would be a better way to sort those words into the dictionary order? Do I have to change each single word to lower case then compare? or we have some better way to compare it?

Kara
  • 6,115
  • 16
  • 50
  • 57
user3923936
  • 73
  • 1
  • 8
  • 3
    Strongly related: http://stackoverflow.com/questions/11635/case-insensitive-string-comparison-in-c – chris Aug 19 '14 at 04:00
  • @user3923936 What is "the list of strings"? Are they character arrays or something else? – Vlad from Moscow Aug 19 '14 at 04:06
  • A function for case insensitive comparison of strings is available at http://stackoverflow.com/a/17330790/434551. – R Sahu Aug 19 '14 at 04:07
  • 1
    Given a case insensitive comparison function as per comments above, sorting a `std::list` involves calling the [`sort` member function](http://en.cppreference.com/w/cpp/container/list/sort) with a `Compare` functor invoking the insensitive comparison (checking the first arg is less than the second). If you don't mean `list` literally, then use [`std::sort`](http://en.cppreference.com/w/cpp/algorithm/sort) with iterators and a similar comparison functor. – Tony Delroy Aug 19 '14 at 04:15

1 Answers1

0

Use std::sort (or std::stable_sort if you want to preserve the order of elements) with a comparison function:

std::sort(list.begin(), list.end(), caseInsensitiveComparison);
std::stable_sort(list.begin(), list.end(), caseInsensitiveComparison);

where caseInsensitiveComparison is the case-insensitive comparison function, a binary function returning whether the first argument string should go before the second in the dictionary. As pointed out by earlier comments, look at this question about how to implement case-insensitive comparisons.

jotik
  • 17,044
  • 13
  • 58
  • 123
  • I'm not sure about std::sort, but for std::stable_sort, the compare is done with the parameters reversed, a "later" element (first parameter to compare) is compared to an "earlier" element (second parameter to compare), and the expected result is the compare returns true if the "later" element is "less than" the "ealier" element, in which case the elements are out of order. For std::sort, it doesn't make much difference, but for std::stable_sort, it preserves the original order if the elements are equal. – rcgldr Aug 19 '14 at 05:17