【问题标题】:Taking user input to define the value of a variable in the private section C++接受用户输入来定义私有部分 C++ 中的变量值
【发布时间】:2015-02-26 21:29:20
【问题描述】:

我正在用 C++ 创建一个哈希表,但我的 C++ 有点生疏。 在预定义哈希表的大小时,我可以很好地编写所有代码,但是,我希望用户能够确定他们希望哈希表有多大。

目前在我的 Hash.h 文件的私有部分中,我有以下代码..

    // static const int tableSize = 10;
    static const int tableSize = 100;

    //Types of things that the item consists of

    struct item {

        string name;

        string drink;

        item* next; //Point to next item in the hash table
    };

    item* HashTable[tableSize];

};

我的目标是让 tableSize 变量成为用户输入的整数。这样做的最佳方法是什么?

【问题讨论】:

  • 使用std::vector<item *>
  • 如果你使用std::liststd::vector,你可以放下next指针,因为顺序基本上是由列表或向量中的位置来处理的。
  • 是否不能让用户输入一些可变整数值并将其分配给他们想要使用的表大小?这就是它应该制作的方式。

标签: c++ hashtable


【解决方案1】:

您可以将项目的 const 向量与可变列表一起使用。

常量向量应该用它的大小来初始化,它不会让你添加更多的条目,可变列表会让你向它添加项目。

在这里你可以看到一个示例:

struct item{

};

struct items{
    mutable list<item> entry;
};

int main() 
{ 
    int n;
    cin>>n;
    const vector<items> hashtable(n); 

    /*
      hashtable.push_back(...) is illegal.
      You can't add elements to it, since it is const, 
      so the initialized size will be fixed.

      BUT: list is changeable since it mutable, 
      so the following is legal:
     */
    int i = 0
    item t;
    hashtable[i].entry.push_back(t); 

【讨论】:

  • 因此,如果我按照我已经编程的方式进行操作,是否可以执行类似 int tSize; 的操作?然后调用 cin >> tSize。有一些变化吗?
  • 你所能做的就是使用动态分配,因为全局数组不能在c++中重新分配,
  • 那么有没有办法让用户定义数组的大小?我需要使用数组,而不是向量。
  • 那么创建一个动态数组.. 使哈希表成为一个动态数组。
  • item** HashTable= new item*[tableSize];
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多