有人可以解释一下这行代码:
pq.push( Key { count[c-'a'], c} )
重载运算符如何为此代码工作?
为什么我无法更改此特定行
bool operator <(const Key &k) const
指向此特定operator>
bool operator >(const Key &k) const
完整代码如下:
const int MAX_CHAR = 26;
struct Key
{
int freq;
char ch;
bool operator <(const Key &k) const
{
return freq < k.freq;
}
};
void rearrangeString(string str)
{
int n = str.length();
int count[MAX_CHAR] = {0};
for (int i = 0 ; i < n ; i++)
{
count[str[i]-'a']++;
cout<<"count "<<str[i]-'a'<<" "<<count[str[i]-'a']<<" "<<endl;
}
priority_queue< Key > pq;
for (char c = 'a' ; c <= 'z' ; c++)
if (count[c-'a'])
pq.push( Key { count[c-'a'], c} );
cout<<endl<<pq.top().ch;
str = "" ;
Key prev {-1, '#'} ;
while (!pq.empty())
{
Key k = pq.top();
pq.pop();
str = str + k.ch;
if (prev.freq > 0)
pq.push(prev);
(k.freq)--;
prev = k;
}
if (n != str.length())
cout << " Not valid String " << endl;
else
cout << str << endl;
}
int main()
{
string str = "bbbaa" ;
rearrangeString(str);
return 0;
}
答案 0 :(得分:3)
Key { count[c-'a'], c}
通过将Key
初始化为freq
并将count[c-'a']
初始化为ch
来构建c
个对象。然后该对象作为参数传递给pq.push
调用。
operator >
不起作用,因为您是默认比较器使用Key
的{{1}}中的std::priority_queue
。要改为使用<
,请像这样声明>
:
pq