【发布时间】:2019-11-06 19:12:06
【问题描述】:
我有一个嵌套在 LinkedList 类中的迭代器类。我的问题是如何使用迭代器制作 insert_after 函数。其余代码仅供参考,但我尝试使用的功能在最后。
Insert_After 获取一个位置并在其后插入一个值。
template <typename T>
class LinkedList : public LinkedListInterface<T> {
private:
struct Node {
T data; // data can be any type
Node* next; // points to the next Node in the list
Node(const T& d, Node* n) : data(d), next(n) {}
};
Node* head; // Is a pointer
class Iterator
{
private:
Node* iNode;
public:
Iterator(Node* head) : iNode(head){ }
~Iterator() {}
bool operator!=(const Iterator& rhs) const { return iNode != rhs.iNode; }
Iterator& operator++() { iNode = iNode->next; return *this; }
T& operator*() const { return iNode->data; }
};
/** Return iterator pointing to the first value in linked list */
Iterator begin(void) {
return LinkedList<T>::Iterator(head);
}
/** Return iterator pointing to something not in linked list */
Iterator end(void) {
return LinkedList<T>::Iterator(NULL);
}
/** Return iterator pointing found value in linked list */
Iterator find(Iterator first, Iterator last, const T& value) {
Iterator current = first;
bool found = false;
while (current != last) {
if (*current == value) {
return current;
}
++current;
}
return last;
}
Iterator insert_after(Iterator position, const T& value)
{
// Need help here
}
到目前为止,我的尝试导致了一些错误。
Iterator insert_after(Iterator position, const T& value)
{
// Need to insert after position
Iterator previous = position;
++position;
Node* newNode = new Node(value, position);
previous->next = newNode;
}
我得到的错误是 Error C2664 'function' : cannot convert argument n from 'type1' to 'type2' for the line
Node* newNode = new Node(value, position);
编译器错误 C2819 类型 'type' 没有用于行的重载成员 'operator ->'
previous->next = newNode;
我了解这些错误,但我不确定如何解决它们。
【问题讨论】:
-
到目前为止您尝试了什么,遇到了什么错误。请阅读How to Ask 和minimal reproducible example。