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

时间:2016-09-09 15:53:53

标签: c++ sorting vector normalization

我对编程仍然比较陌生,我已经做了很多关于如何实现这一点的研究,但我无法弄明白。

我一直在使用这种不区分大小写的排序:

    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类型的向量之前,哪个工作正常。如何使这种排序对所有数据类型都是通用的,同时仍然使它不区分大小写?

1 个答案:

答案 0 :(得分:2)

您可以将std::sort()与您自己的比较功能一起使用。

再见,我认为你不需要对所有数据类型都不区分大小写。

对于您的评论:如果您想进行默认比较,则可以随时忽略第3个参数。

示例:

#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 << ' ';}
}