简体   繁体   中英

sort strings in dictionary order c++

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM