不区分大小写的c++排序,接受所有数据类型
Case insensitive c++ sort that accepts all datatypes?
我对编程还是比较陌生的,我已经做了很多关于如何实现这个的研究,但我不能弄清楚。
我一直在使用这个大小写不敏感的排序:
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 << ' ';}
}
相关文章:
- 防止主数据类型C++的隐式转换
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 在C++中打印指向不同基元数据类型的指针的内存地址
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 如何对点云数据进行排序
- 如何计算数据类型的范围,例如int
- C++中数据类型修饰符的顺序
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- 特定数据类型的模板类
- 具有多个模板的模板函数,用于特定数据类型(如字符串)?
- 有没有办法提示用户使用哪种数据类型作为模板 c++
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 时间复杂度 当具有复合数据类型(如元组或对)时?
- 为什么我的气泡排序不适用于双精度数据类型?
- c++我需要将文件中的数据读取到多维数组中,然后用一种数据类型对数组进行排序.怎样
- 使用std::sort与自定义排序对象和数据类型模板-寻找正确的语法
- 无法理解未排序列表和通用数据类型
- 数据类型-排序和代码大小
- 对抽象数据类型的stl::列表排序
- 不区分大小写的c++排序,接受所有数据类型