Cpp关于static关键字的问题

Cpp关于static关键字的问题

Leetcode 706. 设计哈希映射。
为什么base和hashfunc需要设置为static,不然就会报错(报错内容附下)。static在这里起了什么作用?

class MyHashMap {
public:
    vector<list<pair<int,int>>> data;
    static const int base = 769;//为什么必须使用static?
    static int hashfunc(int k){
        return k % base;
    }
    MyHashMap(): data(base) {

    }
    
    void put(int key, int value) {
        int adr = hashfunc(key);
        for(auto it = data[adr].begin();it!=data[adr].end();it++){
            if(it->first == key){
                it->second = value;
                return;
            }
        }
        data[adr].push_back(make_pair(key, value));
    }
    
    int get(int key) {
        int adr = hashfunc(key);
        for(auto it = data[adr].begin();it!=data[adr].end();it++){
            if(it->first == key){
                return it->second;
            }
        }
        return -1;
    }
    
    void remove(int key) {
        int adr = hashfunc(key);
        for(auto it = data[adr].begin();it!=data[adr].end();it++){
            if(it->first == key){
                data[adr].erase(it);
                return;
            }
        }
        return;
    }
};

执行出错信息:
terminate called after throwing an instance of 'std::length_error'
  what():  cannot create std::vector larger than max_size()
最后执行的输入:
["MyHashMap","put","put","get","get","put","get","remove","get"]
[[],[1,1],[2,2],[1],[3],[2,1],[2],[2],[2]]

简单说, 构造一个对象的顺序是从上到下, data在base前, 却要用base的值, 那么基本就是个垃圾值,
*
而加了static, 意味着base属于类不属于对象, 那么它自类声明起, 就已经产生, 于是你在构造对象时data可以用正确的base值了.
*
至于hash函数, 是不是static我没看出有什么区别.

在代码中,将base和hashfunc设置为static的目的是为了确保它们在整个类的实例中是共享的,而不是每个对象实例都有自己的副本。

  1. static const int base = 769;
    这里将base声明为静态常量,它的值在整个类的所有实例中是不变的。由于哈希映射的容量应该是固定的,将base设置为静态常量可以确保所有实例共享相同的容量值,并且可以在不创建对象实例的情况下访问。

  2. static int hashfunc(int k)
    hashfunc函数也被声明为静态函数。静态函数属于类本身,而不是类的实例。在这个特定的情况下,hashfunc函数不依赖于任何对象的状态,它只根据传入的参数进行计算。因此,将其声明为静态函数可以直接在类范围内调用,而无需实例化类对象。

将base和hashfunc声明为静态的好处是它们可以被类的所有实例共享,并且可以在没有实例的情况下访问它们。在哈希映射的实现中,这是非常有用的,因为它们代表了共享的数据和功能,而不是依赖于特定的对象实例。

至于你遇到的报错信息:"terminate called after throwing an instance of 'std::length_error' what(): cannot create std::vector larger than max_size()",它是因为vector的大小超过了其最大容量限制。这可能是由于哈希映射的容量过大,超过了vector支持的最大大小。检查您的代码逻辑,确保容量设置合理,并且没有无限循环或其他问题导致容量增长过快。