简体   繁体   中英

Vector with index and iterator

I just wanted to ask what is happening here, where am I going wrong?

vector<int> a(5);

for(int i=0; i<5; i++)    cin>>a[i];            //Input is 1 2 3 4 5

for(int i=0; i<5; i++)    cout<<a[i]<<" ";      //Prints correct, 1 2 3 4 5
cout<<endl;

for(VI::iterator it = a.begin(); it!=a.end(); ++it) {
    cout<<a[*it]<<" ";                          //Prints incorrect output
}
cout<<endl;

Looks like, the last element in the incorrect output is a[*(a.end()-1)] and the first element is missing from what it should actually be.

correct way to print is

 cout<<*it<<" ";   

*it gives value pointed by vector. In your case a[*it] = a[1] for first iteration, a[2] for second iteration ans so on. at end invalid number will be printed. Its the reason for missing first number. Your trying to print a[1] a[2], a[3],a[4],

By calling *it you are getting the value at that iterator (which is what I think you want to output). You're current code is actually doing:

a[1]
a[2]
a[3]
a[4]
a[5] // not an element in the vector - undefined behaviour

What I think you actually want is:

cout<<*it<<" ";

What happens here

for(VI::iterator it = a.begin(); it!=a.end(); ++it) {
  cout<<a[*it]<<" "; // *it is 1, 2, 3, 4, 5
}

is that it is an iterator to each element of the vector, and *it dereferences the iterator, giving the value of the element. Since the indices and the values stored are almost the same in this case, this almost works. You are looping from a[1] to a[5], missing the first element, and then going out of bounds.

Iterator is not an index to a vector. It is an object that points to an element of the vector and has overloaded dereference operator that yields the value of the element pointed by that iterator.

When you do a[*it] , you essentially use the value of an element stored in the vector (pointed by it ) as an index to that array. In other words, you are referencing elements 2 though 6, and also invoke undefined behavior because there is no 6th element in your vector.

You have probably meant to write cout<<*it<<" "; instead of cout<<a[*it]<<" "; . Or, alternatively, given your data set in that vector, you could do cout<<a[*it - 1]<<" "; in order to access elements 1 through 5 by using index 0 through 4.

Hope it helps. Good Luck!

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