开发者

C++ Linked List: Overload bracket operators []

开发者 https://www.devze.com 2023-04-12 02:58 出处:网络
So, I decided to look back at some data structures to keep myself sharp ;) I started to implement a hash table, when I remembered that I needed linked lists for the buckets so that I can avoid hash c

So, I decided to look back at some data structures to keep myself sharp ;)

I started to implement a hash table, when I remembered that I needed linked lists for the buckets so that I can avoid hash collisions. So I started my linked list...

I implemented all of the functional methods of my linked list class (add, get, remove, etc) and then I decided that I wanted to try something that I hadn't tried before. Overloading the array index operators so that my linked list indexes can be retrieved or assigned as if the linked list was an array.

I got the retrieval part working no problem:

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

The get function returns the data of the associated node, not the node itself...the setter should behave where the value supplied gets stored to the data attribute of node at the given index...my vision is that the user will not ever have to touch the ListNode class.

My end goal is that I can have a smart LinkedList that will behave like so:

LinkedList<int> list;

list[0] = 1; 开发者_StackOverflow社区   //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

The getter works fine, but I am having trouble on the setter. Assume the set function with all index error checking and memory allocation is done, as it is. Any help would be appreciated. If it is impossible, then please let me know before I spend more time on it. Thanks.


it looks like you want to return nodes by reference:

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); }
...
};

(also assumes LinkedList::get() returns references)


operator[] and get() should return a reference to the data.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号