这里的 strcmp 和 c_str() 有什么问题?

What's wrong with strcmp and c_str() here?

下面的代码是我针对Largest Number的解决方案。但是它会崩溃。

如果我用tempa > tempb而不是strcmp()直接比较cmp()中的tampatempb,就可以了。那么这里有什么问题?

#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;
}

您的比较不等于 tempa > tempb。它相当于 !(tempa < tempb)tempa >= tempb。而一个"greater than or equal"比较不满足std::sort的要求。具体来说,比较需要是非自反的,也就是说对于操作数 A,cmp(A, A) 应该是假的,但是对于 >=,它是真的。

如果您想要 tempa > tempbstrcmp 等价物,请执行以下操作:

return strcmp(tempa.c_str(), tempb.c_str()) > 0;

仔细检查后,您的比较从根本上被打破了。为什么要将 ab 连接在一起以形成用于比较的临时字符串?作为那里可能出错的一个简单示例,一个空字符串将与其他所有字符串进行比较,因为:

(string("anything") + "") == (string("") + "anything")