簡體   English   中英

C ++鏈接列表:重載括號運算符[]

[英]C++ Linked List: Overload bracket operators []

所以,我決定回顧一些數據結構,以保持自己的銳利;)

我開始實現一個哈希表,當我記得我需要桶的鏈表以便我可以避免哈希沖突。 所以我開始了我的鏈表......

我實現了我的鏈表類的所有功能方法(添加,獲取,刪除等),然后我決定嘗試一些我之前沒有嘗試過的東西。 重載數組索引運算符,以便可以檢索或分配我的鏈表索引,就像鏈表是一個數組一樣。

我的檢索部分沒有問題:

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函數按原樣完成。 任何幫助,將不勝感激。 如果不可能,請在我花更多時間之前告訴我。 謝謝。

看起來你想通過引用返回節點:

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()返回引用)

operator[]get()應該返回對數據的引用。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM