【发布时间】:2015-12-10 17:53:51
【问题描述】:
我在传递我使用命令行从用户那里获取的变量(array_size)时遇到问题。我需要将此变量传递给 HashMap 构造函数。在构造函数中,如果我将“array_size”更改为 f.e 1000,它可以工作,但我需要它是“变量”:) 这是我的代码,我非常感谢任何帮助。 干杯。
#include<iostream>
#include<cstdlib>
using namespace std;
int counter = 1;
class HashEntry
{
public:
string key, value;
HashEntry(string key, string value)
{
this->key = key;
this->value = value;
}
};
class HashMap
{
private:
HashEntry **table;
public:
HashMap()
{
table = new HashEntry*[array_size];
for (int i = 0; i < array_size; i++)
table[i] = NULL;
}
void put(string key, string value, int option, int array_size)
{
int _key = atoi(key.c_str());
int hash = _key;
if(option == 1)
{
while (table[hash] != NULL && table[hash]->key != key)
{
counter++;
hash = (hash + 10);
}
hash = hash % array_size;
}
else if(option == 2)
{
while (table[hash] != NULL && table[hash]->key != key)
{
counter++;
hash = (hash + 10 + counter*counter) % array_size;
}
}
else if(option == 3)
{
while (table[hash] != NULL && table[hash]->key != key)
{
counter++;
hash = (hash + counter*(_key%(array_size-2)+1));
if(hash >= array_size)
{
hash = 0;
}
}
hash = hash % array_size;
}
if(table[hash] == NULL)
{
table[hash] = new HashEntry(key, value);
}
else
{
if (table[hash] != NULL && table[hash]->key == key)
{
table[hash]->value;
}
else
{
table[hash] = new HashEntry(key, value);
}
}
}
};
int main(int argc, char* argv[])
{
HashMap map;
string key, value;
int array_size;
array_size = atoi(argv[2]);
int option = atoi(argv[1]);
int records;
cin>>records;
for(int x = 0; x<records; x++)
{
cin >> key;
cin >> value;
map.put(key, value, option, array_size);
}
cout << counter << endl;
return 0;
}
【问题讨论】:
-
要从命令行获取整数值,接受它作为
main()中的字符串数组项或WinMain()中的字符串,具体取决于您的平台,转换argv[1]或使用strtol()的另一个参数或模拟一个整数值,然后将其传递给构造函数。你应该在你的 C 教科书中得到确切的细节。这一切都与对象的构造毫无共同之处,后者主要是另一个话题。
标签: c++ variables constructor parameter-passing