gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:38:41 25 4
gpt4 key购买 nike

我对编程还是比较陌生,我已经对如何实现它做了很多研究,但我想不通。

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

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

在我传入一个字符串类型的 vector 之前,它工作正常。我怎样才能使这种排序对所有数据类型通用,同时仍然使其不区分大小写?

最佳答案

您可以将 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 << ' ';}
}

关于c++ - 接受所有数据类型的不区分大小写的 C++ 排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39415431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com