1

我有一个结构项目向量,里面有一个字符串。我试图通过在项目中按字母顺序排列字符串来对项目向量进行排序......到目前为止我有:

vector<Item> sorter;

std::sort(sorter.begin(), sorter.end(), SortHelp);

//predcate function
bool SortHelp(Item const& one, Item const& two) 
{
    return one.type < two.type;
}

*type 是我用来排序的字符串

如何更改谓词函数以按字母顺序对字符串进行排序?

4

2 回答 2

2

以下函数将在没有外部库的情况下对两个 s 进行不区分大小写的比较std::string(尽管它是 C++11)。

bool caseinsensitivecompare(string s1, string s2) {
    locale loc;
    std::transform(s1.begin(),s1.end(),s1.begin(), 
                   [loc](char c){return std::toupper<char>(c,loc);});
    std::transform(s2.begin(),s2.end(),s2.begin(), 
                   [loc](char c){return std::toupper<char>(c,loc);});
    return (s1 < s2);
}
于 2013-02-10T03:21:38.227 回答
0

正如不区分大小写的字符串比较 C++ (2012)中所建议的,如果比较字符串,strcasecmp()将提供正确的答案。const char *

如果比较 C++ 字符串,Boost 库有is_iless(),其标头在此处,正如C++ (2008) 中不区分大小写的字符串比较所建议的那样。

于 2013-02-10T02:26:58.217 回答