// Expect to print values of arr[0] to arr[4]
    #include <iostream>
    #include <vector>
    using namespace std;
    int main() {
        vector<int *> ptrList;
        int arr[] = { 0, 10, 20, 30, 40 };
        int * ptrArr = arr;
        for( int i=0; i< 5; i++ ) {
            ptrList.push_back( ptrArr+i );
        }
        vector<int *>::iterator itr = ptrList.begin();
        for( int i=1; i<= 5; i++ ) {
            cout << **itr-1 << endl;
            itr++;
        }
        return 0;
    }

somebody help me please...dunno where i went wrong :(

Recommended Answers

All 7 Replies

At line 12 you've declared an iterator: vector<int *>::iterator itr = ptrList.begin();
So just use it to iterate through the vector.

 vector<int *>::iterator itr = ptrList.begin();
 for( itr; itr < ptrList.end(); ++itr ) {
     cout << **itr << endl;
 }

Beat me to it again!
I'll just add that itr isn't directly affected by i, so the first run through when itr is at the beginning, itr-1 is pointing at something that's not there.

Take of the code from line 12-16 and use this
dont forgrt to include the algorithm lib

for_each(ptrList.begin(),ptrList.end(),[](int *c){ cout << *c-1;});

for_each(ptrList.begin(),ptrList.end(),[](int *c){ cout << *c-1;});

It should just be cout << *c, otherwise it's subtracting 1 from each value.
ie. -1, 9, 19 etc

for_each(ptrList.begin(), ptrList.end(), [](int *c){ 
    cout << *c << "\n";
});

Are you guessing?
Check the op's code before you comment. goto line 12-16. What do you see?...

Also you provided nothing new and no solution to the op. Check first. ))

Another way to print the values pointed to by the vector is to use C++11's new range-based for loops (if you have an up-to-date compiler). This way, you don't even have to declare your own iterator.

for(auto ptr : ptrList)
    cout << *ptr << endl;

Are you guessing?
Check the op's code before you comment. goto line 12-16. What do you see?...

Also you provided nothing new and no solution to the op. Check first. ))

I assume you're addressing me?
1. No, I'm not guessing.
2. line 1: Expect to print values of arr[0] to arr[4]. So at lines 12 to 16 I see an obvious mistake.
3. I always check. I have no interest in posting for the sake of increasing my post count.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.