[英]how to write a default iterator to a generic list?
我正在編寫此代碼的通用列表,現在在該通用列表中,我為迭代器做了一個類,它包含兩個參數:一個是指向他指向的列表的指針。 另一個指向他所指向的列表中的元素。
現在,我需要編寫一個insert函數,將一個新元素插入到給定列表中,並具有以下規則::在這里,我向列表中插入一個新節點,如果迭代器指向列表的末尾,則在此函數中,我們將新節點添加到列表的末尾,否則我們在迭代器當前指向的節點之前一個位置插入該節點,如果iteratot指向另一個節點,那就是錯誤。
現在我希望迭代器不存在,因此在測試中有人用一個參數調用了函數,我希望迭代器等於列表的結束元素。 函數結束我將其寫在列表中。 現在在插入功能,我做到了,但我得到這個錯誤:
不能在沒有對象的情況下調用成員函數“ List :: iterator List :: end()”。
#include <iostream>
#include <assert.h>
#include "Exceptions.h"
template <class T>
class List {
public:
List();
List(const List&);
~List();
List<T>& operator=(const List& list);
template <class E>
class ListNode {
private:
ListNode(const E& t, ListNode<E> *next): data(new E(t)), next(next){}
~ListNode(){delete data;}
E* data;
ListNode<E> *next;
public:
friend class List<E>;
friend class Iterator;
E getData() const{
return *(this->data);
}
ListNode<E>* getNext() const{
return this->next;
}
};
class Iterator {
const List<T>* list;
int index;
ListNode<T>* current;
Iterator(const List<T>* list, int index): list(list),
index(index),current(NULL){
int cnt=index;
while (cnt > 0) {
current = current->next;
cnt--;
}
}
friend class List<T>;
friend class ListNode<T>;
public:
// more functions for iterator
};
Iterator begin() const ;
Iterator end() const;
void insert(const T& data, Iterator iterator=end());//here i get the error
void remove(Iterator iterator);
class Predicate{
private:
T target;
public:
Predicate(T i) : target(i) {}
bool operator()(const T& i) const {
return i == target;
}
};
Iterator find(const Predicate& predicate);
class Compare{
private:
T target;
public:
Compare(T i) : target(i) {}
bool operator()(const T& i) const {
return i < target;
}
};
bool empty() const;
int compareLinkedList(ListNode<T> *node1, ListNode<T> *node2);
private:
ListNode<T> *head;
ListNode<T> *tail;
int size;
};
任何幫助都將是驚人的! 因為我不知道為什么這樣的錯誤會消失。
//insert function just in case :
template <typename T>
void List<T>::insert(const T& data, Iterator iterator=end()){
if(iterator.list!=this){
throw mtm::ListExceptions::ElementNotFound();
return;
}
ListNode<T> *newNode = new ListNode<T>(data, iterator.current);
if(iterator.index==size){
if (head == NULL) {
head = newNode;
tail=newNode;
}else{
Iterator temp(this,size-1);
temp.current->next=newNode;
}
//newNode->next=this->end().current;
}
else {
if (head == NULL) {
head = newNode;
tail=newNode;
}
else {
Iterator temp1(this,iterator.index-1);
temp1.current->next=newNode;
newNode->next=iterator.current->next;
}
}
size++;
}
void insert(const T& data, Iterator iterator=end());
這是違規行。 默認參數不能是成員函數調用的結果。 實現您想要的正確工具是過載。
void insert(const T& data, Iterator iterator);
void insert(const T& data) { insert(data, end()); }
在這里,我們仍然遵循您實現的insert函數,但是我們在允許重載的地方調用end
。
不用擔心間接調用。 這是一個非常小的函數,它在類聲明本身內部定義。 任何體面的編譯器都會完全內聯它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.