【发布时间】:2016-07-07 14:37:35
【问题描述】:
我正在解决字符串数组的排序非冗余排列问题。
例如,如果输入字符串是"8aC",那么输出应该是像{"Ca8","C8a", "aC8", "a8C", "8Ca", "9aC"}这样的顺序。我选择了C++数据结构集,因为每次我将字符串插入std:set时,集都会自动排序并消除冗余。输出很好。
但我想以不同于默认字母数字排序顺序的不同字母数字顺序排序集。我想自定义设置顺序优先级的比较器,例如:upper case> lower case > digit。
我尝试自定义比较器,但非常令人沮丧。 如何自定义集合的排序顺序?这是我的代码。
set<string, StringCompare> setl;
for (i = 0; i < f; i++)
{
setl.insert(p[i]); //p is String Array. it has the information of permutation of String.
}
for (set<string>::iterator iter = setl.begin(); iter != setl.end(); ++iter)
cout << *iter << endl; //printing set items. it works fine.
struct StringCompare
{
bool operator () (const std::string s_left, const std::string s_right)
{
/*I want to use my character comparison function in here, but have no idea about that.
I'm not sure about that this is the right way to customize comparator either.*/
}
};
int compare_char(const char x, const char y)
{
if (char_type(x) == char_type(y))
{
return ( (int) x < (int) y) ? 1 : 0 ;
}
else return (char_type(x) > char_type(y)) ? 1 : 0;
}
int char_type(const char x)
{
int ascii = (int)x;
if (ascii >= 48 && ascii <= 57) // digit
{
return 1;
}
else if (ascii >= 97 && ascii <= 122) // lowercase
{
return 2;
}
else if (ascii >= 48 && ascii <= 57) // uppercase
{
return 3;
}
else
{
return 0;
}
}
【问题讨论】:
-
不要硬编码 ASCII 码。
x >= '0'读起来比ascii >= whatever_is_ascii_code_for_zero干净得多(懒得去查了)。但是isdigit(x)比任何一个都好。
标签: c++ algorithm set std comparator