下面的程序给出错误invalid use of mep in static function
当我将mep声明为静态给定为错误undefined reference to mep
当我宣布comp为非静态并且mep为非静态时
我给错误invalid use of non static member in sort
我应该怎么用leetcode提交这个解决方案类?
class Solution {
public:
unordered_map<char,int>mep;
static bool comp(string a,string b){
int n = min(a.size(),b.size());
for(int i=0;i<n;i++){
int diff = mep[a[i]]-mep[b[i]];
if(diff<0)return false;
if(diff>0)return true;
}
return true;
}
bool isAlienSorted(vector<string>& words, string order) {
for(int i=0;i<order.size();i++){
mep[order[i]]=i;
}
vector<string>temp;
temp=words;
sort(temp.begin(),temp.end(),comp);
return temp==words;
}
};
我知道比较器的另一种方法可以是lambda函数,以上或lambda哪个有效?
最佳答案
声明一个自定义比较器类型,将其用作std::sort
最终比较器参数的基础。在此过程中,您将获得可重用性。 static
实现非常缺乏。
class Solution {
public:
struct Comp
{
unordered_map<char, int> mep;
bool operator()(std::string const& a, std::string const& b)
{
size_t n = min(a.size(), b.size());
for (size_t i = 0; i<n; i++) {
int diff = mep[a[i]] - mep[b[i]];
if (diff<0)
return false;
if (diff>0)
return true;
}
return true;
}
};
bool isAlienSorted(vector<string> const& words, string order)
{
Comp comp;
for (int i = 0; i<order.size(); i++) {
comp.mep[order[i]] = i;
}
vector<string>temp = words;
sort(temp.begin(), temp.end(), comp);
return temp == words;
}
};
关于您的最后一个问题,请编译为经过优化的代码,并使用完善的基准测试(听起来并不容易)。即使有明显的差异,我的钱也就花在了lambda上(无论如何,这几乎就是我们上面的钱),其原因无非是因为编译器更有可能在
std::sort
扩展中内联比较器。
关于c++ - 静态cpp中的非静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59528337/