#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
int order[26];
struct lexcmp
{
bool operator()(const string &s1,const string &s2)
{
int i=0;
int j=min(s1.size(),s2.size());
while(1)
{
if(order[s1[i]-'a']<order[s2[i]-'a'])
return true;
if(order[s1[i]-'a']>order[s2[i]-'a'])
return false;
if(i==j-1)
return false;
i++;
}
}
};
int main()
{
string s;
cin>>s;
for(int i=0;i<s.size();i++)
{
order[s[i]-'a']=i;
}
set<string,lexcmp> store;
int m;
cin>>m;
while(m--)
{
string q;
cin>>q;
store.insert(q);
}
for(auto i=store.begin();i!=store.end();i++)
{
cout<<*i<<endl;
}
}
return 0;
}
- 制作自定义函数对象时的问题 问题是,我有一种新的元素顺序(而不仅仅是 a-z)。//保存在排序数组中
- 我只想基于新顺序对给定字符串进行排序。
- 例如:顺序是:bacdefghijklmnopqrstuvwxyz 因此,如果字符串是ss,aa,bb, 新的排序将为bb,aa,ss。
- 代码运行良好,但是当字符串像“pas”“p”这样进行比较时,它会给我带来问题。 p应该在pas之前出现,但是它却在之后出现。
- 我应该对函数对象做哪些修改?
bb, aa, ss
,而是aa, bb, ss
?因为在排序中,我们首先比较字符串的第一个字符,然后再根据需要进行进一步比较。在这种情况下,b的顺序确实在a之前,但是由于我们首先比较了第一个字符,所以按照字母顺序,aa会排在bb之前。 - ildjarni++
之前添加if (i == j) return 0;
。 - HolyBlackCatlexcmp
函数还需要处理两个字符串相等的情况。 - nos