简体   繁体   中英

Encapsulated Iterator: operator++ overloading

For a task I have to implement an iterator that encapsulates another iterator and that performs range checking. My functions prev(), next(), begin() and end() work just fine, but I can't get the operator overloading to work (don't have much experience in that matter). Funny thing is, it doesn't show me any errors but when I run it, the program crashes. Would be great if someone could find out why this is, thank you very much.

Here's a part of my code:

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;
}

I believe the problem is you're incrementing testIterator , NOT MyIterator which testIterator is pointing to.

++testIterator;

You probably intended to do:

++(*testIterator);

This mistake could've easily been avoided if you didn't use pointers at all.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM