C++链表:重载括号运算符 []
因此,我决定回顾一些数据结构,以保持自己的敏锐;)
当我记得我需要存储桶的链表以便避免哈希冲突时,我开始实现哈希表。所以我开始了我的链表...
我实现了我的链表类的所有功能方法(添加、获取、删除等),然后我决定尝试一些我以前没有尝试过的东西。重载数组索引运算符,以便可以检索或分配我的链表索引,就像链表是数组一样。
我让检索部分工作没有问题:
template <class T>
T LinkedList<T>::operator[](const int &i) {
return get(i);
}
get 函数返回关联节点的数据,而不是节点本身...设置器应该将提供的值存储到给定索引处的节点的数据属性中...我的愿景是用户永远不必接触 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
getter 工作正常,但我在 setter 上遇到麻烦。假设 set 函数已完成所有索引错误检查和内存分配。任何帮助将不胜感激。如果不可能,请在我花更多时间之前告诉我。谢谢。
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; //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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来您想通过引用返回节点:(
还假设
LinkedList::get()
返回引用)it looks like you want to return nodes by reference:
(also assumes
LinkedList::get()
returns references)operator[]
和get()
应返回对数据的引用。operator[]
andget()
should return a reference to the data.