2014-04-10 22 views
0

我们正在开发一个自定义List类。我们试图实现迭代器和const_iterator及其函数,但是我们的++运算符有问题。 PostFix完全不起作用,并且当我们步入太远时(当前代码是一个只返回最后有效结果的解决方法),PreFix会给我们分段错误。 问题1:如何修复与前缀相关的段错误而无需返回上一个有效元素? (我们试过返回nullptr)。Iterator和const_iterator操作符++后置和前缀

即使我们已经按照互联网上的每个指南<,Postfix也不会迭代。 <

问题2:PostFix为什么不起作用?

代码交&前缀:

List_const_iterator_& operator++() 
    { 
    if(ptr->next_ != nullptr) 
    { 
     ptr = ptr->next_; 
     return *this; 
    } 
    else 
     return *this; 
    } 

    List_const_iterator_ operator++(int unused) 
    { 
    List_const_iterator_ temp(*this); 
    if(ptr->next_ != nullptr) 
    { 
     ptr = ptr->next_; 
     return temp; 
    } 
    else 
     return *this; 
    } 

Testcode(大气压下以后缀):

List<int> list1 {324, 2, 3}; 
    List_const_iterator_<int> clst = list1.cbegin(); 
    clst = clst++; 
    cout << "val: " << clst.ptr->data_ << endl; 
    clst = clst++; 
    cout << "val2: " << clst.ptr->data_ << endl; 
clst = clst++; 
    cout << "val3: " << clst.ptr->data_ << endl; 

输出为后缀:

val: 324 
val2: 324 
val3: 324 

输出,用于前缀:

val: 2 
val2: 3 
val3: 3 <-- This is where we segfault if we don't use the controll. 
+0

鉴于postfix操作符返回旧值,您对clst = clst ++;(除了未定义的行为)有什么期待? – molbdnilo

回答

2

尝试用刚:

clst++; 

代替:

clst = clst++; 

后者复位clst其原始值(好象增量没有发生)。

+0

是的,解决了它! 如果迭代达到我们列表的末尾,您对我们应该做什么有什么想法吗?因为只是返回最后一个有效值在长期看来似乎不是一个很好的解决方法=) –

+0

@JohanHjalmarsson我认为你应该像标准库一样做,并且让它不确定(即只是失败)。迭代应该由调用者通过与“结束”迭代器进行比较来限定。 – molbdnilo

+0

@JohanHjalmarsson:当迭代器到达list1结尾时,它应该与'list1.cend()'进行比较。所以,你可以检查一下,例如。 'for(it = list1.cbegin(); it!= list1.cend(); ++ it){/ * ... * /}' –