按字典顺序排序字符串c ++

时间:2014-08-19 04:00:10

标签: c++ string sorting insertion-sort

我有一个包含以下单词的字符串列表:Amount,bird,ant,Bob,David,case ...... 我需要按照字典顺序对它们进行排序(Amount,ant,bird,Bob,case,David ......)

我使用插入排序,结果输出为前面的所有大写字母,然后是小写字符串(金额,鲍勃,大卫,蚂蚁,鸟,案例......)。

我的问题是将这些单词排序为字典顺序的更好方法是什么?我是否必须将每个单词更改为小写然后进行比较?或者我们有更好的方法来比较它?

1 个答案:

答案 0 :(得分:0)

使用比较功能使用std::sort(或std::stable_sort,如果你想保留元素的顺序):

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

其中caseInsensitiveComparison是不区分大小写的比较函数,二进制函数返回第一个参数字符串是否应该在字典中的第二个之前。正如之前的评论所指出的,请查看this question关于如何实现不区分大小写的比较。

相关问题