c++ - 封装迭代器 : operator++ overloading

标签 c++ vector iterator operator-overloading

对于一项任务,我必须实现一个封装另一个迭代器并执行范围检查的迭代器。 我的函数 prev()、next()、begin() 和 end() 工作得很好,但我无法让运算符重载工作(在这方面没有太多经验)。 有趣的是,它没有向我显示任何错误,但是当我运行它时,程序崩溃了。 如果有人能找出这是为什么,那就太好了,非常感谢。

这是我的部分代码:

class MyIterator{
private:
    vector<int>::const_iterator myBegin;
    vector<int>::const_iterator myEnd;
    vector<int>::const_iterator currentElement;

public:
    MyIterator(vector<int>::const_iterator begin, vector<int>::const_iterator end){

        myBegin = begin;
        myEnd = --end;      //why do I get the address of the element after the last one (just some random address) without decreasing it like that??
        currentElement = begin;
    }


    bool hasNext(){
        if(currentElement == myEnd){
            return false;
        }
        else{
            return true;
        }
    }


    MyIterator& operator++(){
        if(hasNext()){
            currentElement++;
        }
            return *this;
    }

    MyIterator operator++(int)
    {
        MyIterator tmp(*this);
        ++(*this);
        return tmp;
    }

    vector<int>::const_iterator getElement(){
        return currentElement;
    }

};




int main() {

    vector<int> testVector;
    testVector.push_back(8); testVector.push_back(1); testVector.push_back(6); testVector.push_back(5);


    MyIterator * testIterator = new MyIterator(testVector.begin(), testVector.end());

    ++testIterator;
    test = *testIterator->getElement(); cout<<"++: "<<test<<endl;

    return 0;
}

最佳答案

我认为问题在于您正在递增 testIterator,而不是 testIterator 指向的 MyIterator

++testIterator;

您可能打算这样做:

++(*testIterator);

如果您根本不使用指针,这个错误就可以很容易地避免。

MyIterator testIterator = MyIterator(testVector.begin(), testVector.end());

++testIterator;
int test = *testIterator.getElement(); 

cout<<"++: "<<test<<endl; // 1

关于c++ - 封装迭代器 : operator++ overloading,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20366011/

相关文章:

c++ - 我应该将什么设置为 _ITERATOR_DEBUG_LEVEL

c++ - 哪些 STL 算法可以安全地与单遍输入迭代器一起使用?

c++ - 释放 lpsolve 内存

没有线程的 C++ 并行化?

c++ - 无输出转换

Pimpl 习语上下文中的 C++17 自定义迭代器

c++ - 如何在 BN_CLICKED 上启动外部应用程序?

c++ - C++中的隐式类型转换字母

c++ - 通过唯一的成员 ID 来标识对象是个好主意吗?

c++ - vector 的最小值显示为 0