分段故障访问私有类变量 [英] segmentation fault accessing a private class variable

查看:159
本文介绍了分段故障访问私有类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#define TABLE_SIZE 100489 // must be a power of 2
typedef map<string,int> MAP_TYPE;
typedef pair<string, int> PAIR_TYPE;

class HashTable
{
public:                                     //public functions
    HashTable();
    ~HashTable();
    int find(string);
    bool insert(string, int);
private:
    int hash( const char* );
    vector< MAP_TYPE > v;
};

//HashTable constructor
HashTable::HashTable()
{
    vector< MAP_TYPE > v;               //initialize vector of maps
    v.reserve(TABLE_SIZE);                  //reserve table size
    MAP_TYPE m;
    for (int i = 0; i < TABLE_SIZE; ++i)    //fill vector with empty maps
    v.push_back(m);
    cout << v.size();
}

int HashTable::find(string key)
{
    cout << "in find" << '\n';
    //String to const char* for hash function
    const char *c = key.c_str();
    //find bucket where key is located
    int hashValue = HashTable::hash(c);
    cout << hashValue << '\n';
    string s = key;
    cout << v.size(); //Prints 0 but should be TABLE_SIZE
    //look for key in map in bucket
    MAP_TYPE::const_iterator iter = v[hashValue].find(s);
    if ( iter != v[hashValue].end()) //check if find exists
        return iter->second; //return value of key
    else
        return -1; //arbitrary value signifying failure to find key
}

int main()
{
    HashTable my_hash;
    string s = "hi";
    int z = my_hash.find(s);
    cout << z; //should return -1
    return 0;
}



我测试了find函数我的哈希表,分段故障。即使我在find函数中构造了具有正确大小的向量v,那么大小现在是0吗?我不认为它访问相同的变量。哈希函数很好。发生了什么问题?

I'm testing out the find function my hash table but it is returning a segmentation fault. Even though I constructed vector v with the right size in the find function the size is now 0? I don't think it's accessing the same variable. The hash function is fine. What's wrong?

推荐答案

在C ++类变量最好在初始化列表中初始化:

In C++ class variables are best initialized in initialization lists:

HashTable::HashTable() : v(TABLE_SIZE, MAP_TYPE()) // **here**
{}

std :: vector 有一个构造函数,其大小和默认值,你可以调用它。事实上,由于使用的默认值实际上是使用默认构造函数创建的映射,所以您可以实际写入以下内容,因为在这种情况下可以省略第二个参数:

std::vector has a constructor that takes a size and a default value, so you can just call that. In fact, since the default value to use is actually a map created with the default constructor, you could actually just write the following, because the second parameter can be omitted in that case:

HashTable::HashTable() : v(TABLE_SIZE)
{}

这篇关于分段故障访问私有类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆