class Solution
{
public:
bool cmp(string str1, string str2)
{
int sp1, sp2;
for (int i = 0; i < str1.length(); i++)
{
if (str1[i] == ' ')
{
sp1 = i;
break;
}
}
for (int i = 0; i < str2.length(); i++)
{
if (str2[i] == ' ')
{
sp2 = i;
break;
}
}
string s1 = "", s2 = "";
for (int i = sp1 + 1; i < str1.length(); i++)
s1 += str1[i];
for (int i = sp2 + 1; i < str2.length(); i++)
s2 += str2[i];
return s1 <= s2;
}
vector<string> reorderLogFiles(vector<string> &logs)
{
int n = logs.size();
vector<string> ansLog(n);
int start = 0, end = n - 1;
for (auto str : logs)
{
reverse(str.begin(), str.end());
if (str[0] >= 48 && str[0] <= 57)
{
reverse(str.begin(), str.end());
ansLog[end] = str;
end--;
}
else
{
reverse(str.begin(), str.end());
ansLog[start] = str;
start++;
}
}
end++;
reverse(ansLog.begin() + end, ansLog.end());
sort(ansLog.begin(), ansLog.begin() + start, cmp);
return ansLog;
}
};
有人能帮我为什么我在排序中出错吗(ansLog.begin((,ansLog.bgin((+start,cmp(。我使用comparator对向量进行排序,从开始到索引开始-1。
问题链接:https://leetcode.com/problems/reorder-data-in-log-files/
不关注问题的解决方案,只关注错误。如果你也发布你的错误,这会更有帮助。但希望你的错误如下:
error: reference to non-static member function must be called
sort(ansLog.begin(), ansLog.begin() + start, cmp);
^~~
1 error generated.
这里的问题是cmp
方法是非静态类成员,您需要将其与this
及其两个参数绑定。可以有多种解决方案:
- 您可以考虑使用boost::函数来绑定此:
sort(ansLog.begin(), ansLog.begin() + start, boost::bind( &Solution::cmp, this, _1, _2 ));
- 由于此函数不使用任何类属性,因此您可以简单地将其设置为静态,并按照您正在使用的方式使用它
- 我认为更好的方法是使用如下函子:
class Comparator {
public:
bool operator()(string str1, string str2) {
int sp1, sp2;
for (int i = 0; i < str1.length(); i++)
{
if (str1[i] == ' ')
{
sp1 = i;
break;
}
}
for (int i = 0; i < str2.length(); i++)
{
if (str2[i] == ' ')
{
sp2 = i;
break;
}
}
string s1 = "", s2 = "";
for (int i = sp1 + 1; i < str1.length(); i++)
s1 += str1[i];
for (int i = sp2 + 1; i < str2.length(); i++)
s2 += str2[i];
return s1 <= s2;
}
};
并将其用作:
sort(ansLog.begin(), ansLog.begin() + start, Comparator());