C++ 什么';strcmp和c_str()怎么了?
下面的代码是我的解决方案。但是它会崩溃 如果我使用C++ 什么';strcmp和c_str()怎么了?,c++,stl,strcmp,C++,Stl,Strcmp,下面的代码是我的解决方案。但是它会崩溃 如果我使用tempa>tempb而不是strcmp()直接比较cmp()中的tampa和tempb,就可以了。那么这里出了什么问题 #include <iostream> #include <string> #include <stack> #include <vector> #include <climits> #include <cstdio> #include <algor
tempa>tempb
而不是strcmp()
直接比较cmp()
中的tampa
和tempb
,就可以了。那么这里出了什么问题
#include <iostream>
#include <string>
#include <stack>
#include <vector>
#include <climits>
#include <cstdio>
#include <algorithm>
#include <sstream>
#include <cstring>
using namespace std;
bool cmp(string a, string b) {
string tempa = a + b;
string tempb = b + a;
int res = strcmp(tempa.c_str(), tempb.c_str());
if (res < 0) {
return false;
} else return true;
}
class Solution {
public:
string largestNumber(vector<int>& nums) {
vector<string> str;
string res = "0";
if (nums.empty()) {
return res;
}
for (int i = 0; i < nums.size(); ++i) {
stringstream ss;
ss << nums[i];
str.push_back(ss.str());
}
sort(str.begin(), str.end(), cmp);
res = "";
for (int i = 0; i < str.size(); ++i) {
res += str[i];
}
return res[0] == '0' ? "0" : res;
}
};
int main()
{
Solution sol;
int data[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
vector<int> nums(data, data + sizeof(data) / sizeof(data[0]));
string res = sol.largestNumber(nums);
cout << res << endl;
return 0;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
布尔cmp(字符串a、字符串b){
字符串tempa=a+b;
字符串tempb=b+a;
int res=strcmp(tempa.c_str(),tempb.c_str());
如果(res<0){
返回false;
}否则返回true;
}
类解决方案{
公众:
字符串最大数(向量和nums){
载体str;
字符串res=“0”;
if(nums.empty()){
返回res;
}
对于(int i=0;i ss您的比较不等同于tempa>tempb
。它等同于!(tempa
或tempa>=tempb
。以及“大于或等于”比较不满足std::sort
的要求。具体来说,比较需要是不可伸缩的,也就是说,对于操作数A,cmp(A,A)
应该为false,但如果>=
,则为true
如果您需要与tempa>tempb
等效的strcmp
,请执行以下操作:
return strcmp(tempa.c_str(), tempb.c_str()) > 0;
仔细检查后,您的比较从根本上被破坏了。为什么要将a
和b
连接在一起,形成临时字符串进行比较?作为一个简单的示例,一个空字符串将与其他字符串进行相等的比较,因为:
(string("anything") + "") == (string("") + "anything")
非常感谢!就是这样。我以前不知道cmp
应该是无伸缩的。对于这个问题,这里的比较是可以的,因为给定两个整数“12”和“123”,我想告诉你最大的串联是什么,12123
或12312
。