我正在解決一個字符串數組排序非冗餘排列的問題。例如,如果輸入的字符串是"8aC"
,那麼輸出應該是像{"Ca8","C8a", "aC8", "a8C", "8Ca", "9aC"}
那樣的順序。我選擇了C++數據結構集,因爲每次將字符串插入std:set時,set都會自動排序並消除冗餘。輸出很好。C++ std :: set <string>字母數字自定義比較器
但我想排序設置在不同於默認字母數字排序順序的不同字母順序。我想定製設置訂單優先級的比較器,如: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)'比任何一個都好。 –