不区分大小写的c++排序,接受所有数据类型

Case insensitive c++ sort that accepts all datatypes?

本文关键字:数据类型 排序 大小写 c++ 不区      更新时间:2023-10-16

我对编程还是比较陌生的,我已经做了很多关于如何实现这个的研究,但我不能弄清楚。

我一直在使用这个大小写不敏感的排序:

    for (size_t i = 0; i < copy.size() - 1; i++) //use copy vector to organize in ascending order
    {
        int smallest = i;
        for (size_t j = i + 1; j < copy.size(); j++)
        {
            if (tolower(copy[j]) < tolower(copy[smallest])) //normalizes capitals and lowercases
                smallest = j;
        }
        int temp = copy[smallest];
        copy[smallest] = copy[i];
        copy[i] = temp;
    }

直到我传入一个string类型的向量。我怎样才能使这种排序通用于所有数据类型,同时仍然使它不区分大小写?

您可以使用std::sort()与您自己的比较函数。

顺便说一下,我认为您不需要对所有数据类型不区分大小写。

对于你的评论:如果你想要默认比较,你可以忽略第三个参数。

的例子:

#include <string>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cctype>  //toupper
using namespace std;
bool CompareStringCaseInsensitive(const string& lhs,const string& rhs){
   string::size_type common_length = std::min(lhs.length(),rhs.length());
   for(string::size_type i=0;i<common_length;++i){
      if(toupper(lhs[i]) < toupper(rhs[i]))return true;
      if(toupper(lhs[i]) > toupper(rhs[i]))return false;
   }
   if(lhs.length()<rhs.length())return true;
   if(lhs.length()>rhs.length())return false;//can ignore
   return false;//equal should return false
}
int main(){
   vector<string> testdata{"a","B","c","D"};
   cout << "Sort By Default :" << 'n';
   sort(testdata.begin(),testdata.end());
   for(const auto& s : testdata){cout << s << ' ';}
   cout << 'n';
   cout << "Sort CaseInsensitive :" << 'n';
   sort(testdata.begin(),testdata.end(),CompareStringCaseInsensitive);
   for(const auto& s : testdata){cout << s << ' ';}
}