C ++链接列表:重载括号运算符[]

时间:2011-10-08 04:28:28

标签: c++ data-structures operator-overloading linked-list square-bracket

所以,我决定回顾一些数据结构,让自己保持敏锐;)

我开始实现哈希表,当我记得我需要桶的链表以便我可以避免哈希冲突。所以我开始了我的链表...

我实现了链接列表类的所有功能方法(添加,获取,删除等)然后我决定尝试以前没有尝试过的东西。重载数组索引运算符,以便可以检索或分配我的链表索引,就像链表是一个数组一样。

我的检索部分没有问题:

template <class T>
T LinkedList<T>::operator[](const int &i) {
    return get(i);
}

get函数返回关联节点的数据,而不是节点本身...... setter应该在所提供的值存储到给定索引处的节点的data属性的位置...我的愿景是用户将永远不必触及ListNode类。

我的最终目标是我可以拥有一个行为如此的智能LinkedList:

LinkedList<int> list;

list[0] = 1;    //Allocates memory for 0th node and stores 1 as the data
list[3] = 2;    //Allocates memory for 1th,2th,and 3th nodes and sets 2 as the data
                //Unassigned nodes should use default constructors on data

int a = list[3];  //Sets a to 2
cout << list[0] << endl;  //prints 1

吸气剂工作正常,但我在设定器上遇到麻烦。假设具有所有索引错误检查和内存分配的set函数按原样完成。任何帮助,将不胜感激。如果不可能,请在我花更多时间之前告诉我。感谢。

2 个答案:

答案 0 :(得分:3)

看起来你想通过引用返回节点:

template <typename T>
class LinkedList {
...
  T& operator[](const size_t& i) { return this->get(i); }
  const T& operator[](const size_t& i) const { return this->get(i); }
...
};

(也假定LinkedList::get()返回引用)

答案 1 :(得分:1)

operator[]get()应该返回对数据的引用。

template <class T>
T& LinkedList<T>::operator[](const int &i) {
    return get(i);
}