【问题标题】:Programming a custom Map class using an array使用数组编写自定义 Map 类
【发布时间】:2015-01-13 02:09:17
【问题描述】:

我正在尝试使用模板编写自己的地图类实现,而不是使用向量,只使用数组。

我有两个类:存储密钥和数据的元素。

template <typename K, typename DT>
class Element
{
  public:
    K key;
    DT data;
};

还有 Map 类。

私有变量:

template <typename K, typename DT>
class myMap 
{
   typedef Element<K, DT> myElement;

private:
  myElement  *elements;
  int size;

构造函数:

Template <typename K, typename DT>
myMap<K, DT>::myMap()
{
 //An initial map with a size of 10 potential elements.
 size = 10;
 elements = new myElement[size];    
}

好的,我的问题是;在我的插入方法中,它将一个新元素添加到数组中,我在访问数组中的元素数据时遇到了问题。

template <typename K, typename DT>
void myMap<K, DT>::insert(const K &key, const DT &val)
{
 /*A temporary element to store the data which is then stored
 in the array.*/
 myElement *temp = new myElement;
 temp->key = key;
 temp->data = val;

 elements[i]->key //This isn't allowed, It's not letting me access the key for the element at I

 delete temp;
}

我可以这样处理:

elements->key;

基本上我需要能够访问类中的数组并访问元素类中的数据,以便我可以检查键是否已经存在以避免重复。

【问题讨论】:

  • 为什么要使用数组来实现地图?听起来您正在实施 std::vector 而不是地图。
  • @CaptainObvlious 也许他在学习?

标签: c++ arrays class map associative-array


【解决方案1】:

使用elements[i].key

elements 数组是一个指针,但是当您对它进行数组索引时,您只会得到一个常规的旧 myElement 对象。

通常编译器的错误信息对此非常清楚。我会回去重读你得到的错误。

【讨论】:

  • 。运算符似乎也不起作用,也没有错误消息。会不会是数组的声明方式?
  • 没有。这可能是另一个不相关的错误。这是一些使用 .运营商:codeshare.io/OLwiW
  • 谢谢,我认为问题更多与 Visual Studio Intellisense 有关,它没有显示数组的代码完成,但它可以编译并且似乎工作正常。如果这有意义的话。
猜你喜欢
  • 1970-01-01
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-12
  • 2023-03-04
  • 2022-06-29
  • 1970-01-01
相关资源
最近更新 更多