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;iss您的比较不等同于
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