如何解决排序函数不将参数传递给比较函数
代码的目的是排列给定的整数数组,使它们形成最大的数字。由于溢出问题,输出应该是一个字符串。 该代码非常适合输入-
n = 5
nums = [0,0]
但是同样的代码对输入不起作用 -
n = 27
nums = [0,0]
经过几个小时的尝试,我发现错误出在排序行中。你能帮我找出错误的原因吗? sort(strs.begin(),strs.end(),compareStr);
#include <bits/stdc++.h>
using namespace std;
bool compareStr(string st1,string st2){
//cout << "st1 -- " << st1 << endl;
//cout << "st2 -- " << st2 << endl;
if (st1.size() == st2.size()){
return (st1 <= st2);
}
else if (st1.size() < st2.size()){
int len = st1.size();
for (int i = 0; i < len ; i++){
if (st1[i] < st2[i]){
return true;
}
else if (st1[i] > st2[i]){
return false;
}
}
return compareStr(st1,st2.substr(len));
}
else {
int len = st2.size();
for (int i = 0; i < len ; i++){
if (st1[i] < st2[i]){
return true;
}
else if (st1[i] > st2[i]){
return false;
}
}
return compareStr(st1.substr(len),st2);
}
}
int main(){
int n;
cin >> n;
vector<int> nums;
for (int i = 0; i < n ; i++){
int k;
cin >> k;
nums.push_back(k);
}
vector<string> strs;
//cout << to_string(11)+"12" << endl;
for (int i = 0; i < nums.size(); i++){
strs.push_back(to_string(nums[i]));
}
cout << strs.size() << endl;
for (int i = 0; i < strs.size(); i++){
cout << i << " - " << strs[i] << endl;
}
sort(strs.begin(),compareStr);
string ans = "";
for (int i = strs.size()-1 ; i >= 0 ; i--){
//cout << strs[i] << endl;
ans = ans+strs[i];
//cout << ans << endl;
}
cout << ans << endl;
}
当我在比较函数中打印 st1 值时,它显示它为空。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。