gpt4 book ai didi

c++ - 访问私有(private)类变量的段错误

转载 作者:行者123 更新时间:2023-11-27 23:27:28 24 4
gpt4 key购买 nike

#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 函数中构造了正确大小的 vector v,但现在大小为 0?我不认为它正在访问同一个变量。哈希函数很好。怎么了?

最佳答案

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

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

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

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

关于c++ - 访问私有(private)类变量的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8351233/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com