我正在创建一个与向量(类项目)非常相似的容器类,并定义了一个迭代器子类。其中一个 ctor 采用两个迭代器参数,并使用它们表示的半开范围构建数据结构(双向链表)。
下面的代码(几乎)适用于使用两个 Sol::iterator 类型的迭代器调用 insert(iterator, iterator) 的情况(由于某种原因,*ita 总是指向正确的值,但 insert(*ita) 调用不'似乎没有增加价值??)。(更大的)问题是插入调用需要适用于所有迭代器类型(例如vector::iterator),而我无法追踪如何使其工作。我试过 typedef / typename T::iterator iterator,但最安静的 g++ 是使用 'typename T::iterator iterator',它返回
g++ ex1.cc -o sol -Wall -Wextra -ansi -pedantic
In file included from ex1.cc:1:0:
Sol.h:87:16: error: expected ‘)’ before ‘ita’
ex1.cc:109:5: error: expected ‘}’ at end of input
In file included from ex1.cc:1:0:
Sol.h:84:3: error: expected unqualified-id at end of input
make: *** [ex1] Error 1
这没有多大意义;至少对我来说。这是粗略的笔触:
template <class T, int find_val = 1, class Compare = std::less<T> >
class Sol{
public:
typedef unsigned int size_type; //typedef'ing class variable types
typedef T key_type;
typedef T value_type;
//typename T::iterator iter;
private:
struct node{ //Used as 'links' in the chain that is the doubly linked list
T data;
node *prev;
node *next;
};
node *head, *tail; //The head and tail of the dll
int find_promote_value; //How much should find() shift a value?
public:
class iterator{
private:
node *no;
friend class Sol;
iterator(node *p) : no(p){
}
public:
iterator() : no(0){
}
iterator operator++(){ //Preincrement
no = no->next;
return *this;
}
iterator operator++(int){ //Postincrement
iterator temp = *this;
++*this;
return temp;
}
iterator operator--(){ //Predecrement
no = no->prev;
return *this;
}
iterator operator--(int){ //Postdecriment
iterator temp = *this;
--*this;
return temp;
}
T operator*(){
return no->data;
}
T *operator->(){
return &no->data;
}
bool operator==(const iterator &rhs){
return no == rhs.no;
}
bool operator!=(const iterator &rhs){
return no != rhs.no;
}
};
Sol() : head(0), tail(0), find_promote_value(find_val){
}
Sol(const Sol &rhs) : head(rhs.head), tail(rhs.tail), find_promote_value(rhs.find_promote_value){
}
typename T::iterator iterator;
Sol(iterator ita, iterator itb){ //Sol.h::87. Problem line
while (ita != itb){
iterator itr = insert(*ita);
std::cout << "Inserting " << *ita << ",printout: " << *itr <<"\n";
//dump();
++ita;
}
}
~Sol(){
clear();
}
iterator insert(T input){
node *n = new node;
n->next = NULL;
n->prev = tail;
n->data = input;
if(!tail){
head = n;
tail = n;
}
else{
tail->next = n;
tail = n;
}
return iterator(tail);
}
};