静态 CPP 中的非静态成员

non static member in static cpp

本文关键字:静态成员 CPP 静态      更新时间:2023-10-16

下面的程序给出错误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扩展中内联比较器的可能性更大。

不能访问静态成员函数中的非静态成员变量。此外,还应在类外部定义静态成员变量。下面的代码工作正常,没有任何编译警告和错误。

#include <string>
#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
static 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 (size_t i = 0; i < order.size(); i++) {
mep[order[i]] = i;
}
vector<string> temp;
temp = words;
sort(temp.begin(), temp.end(), comp);
return temp == words;
}
};
unordered_map<char, int> Solution::mep;

void main()
{
}

下面的程序错误地在静态中使用 mep 无效 功能

因为C++中的静态函数(comp(不能访问非静态变量(mep(

当我声明 mep 也为静态给出时,错误未定义 参考环保部

类的静态变量需要有一个定义,而不仅仅是声明。所以给mep一个初始。

您可以将unordered_map作为参数传递给 comp 函数。这样你就不会访问非静态对象,但它需要你编写自己的排序算法:

static bool comp(const unordered_map<char, int>& map_mep, string a, string b)
{
int n = min(a.size(), b.size());
for (int i = 0; i < n; i++) {
// this way there is no non-static involved
int diff = map_mep[a[i]] - map_mep[b[i]];
if (diff < 0)return false;
if (diff > 0)return true;
}
return true;
}

由于mep不是类的静态成员,因此静态函数无法看到它。您应该将mep设置为static以解决此问题。