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

时间:2015-08-12 10:23:39

标签: c++ stl strcmp

以下代码是我Largest Number的解决方案。然而它会崩溃。

如果我使用tampa代替tempb直接比较cmp()中的tempa > tempbstrcmp(),则可以。那么这里有什么问题?

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

1 个答案:

答案 0 :(得分:2)

您的比较不等同于tempa > tempb。它相当于!(tempa < tempb)tempa >= tempb。并且&#34;大于或等于&#34; 比较不满足std::sort的要求。具体来说,比较需要是反射性的,也就是说对于操作数A,cmp(A, A)应该是假的,但是对于>=,它是真的。

如果您想要strcmp等效于tempa > tempb,请执行以下操作:

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

仔细观察后,您的比较会从根本上被打破。为什么要将ab连接在一起形成临时字符串以进行比较?作为可能出现问题的一个简单示例,空字符串将与每个其他字符串进行比较,因为:

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