In this code vector is used but i don't understand why couldnt i write it differently explained in code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
vector<double>v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
vector<double>::iterator it1=v.begin();
vector<double>::iterator it2=v.end();
cout<<*it1<<","<<*(it2-1)<<endl;
it1+=3;//this works if not commented
it2-=3;//but if commented it shows run error why do we have to add plus
//3 to move pointer to move 3 positions why cant we write just *(it1+3)
cout<<*(it1+3)<<","<<*(it2-3)<<endl;
it1--;
it2++;
cout<<*it1<<","<<*it2<<endl;
cout<<it1[1]<<","<<it2[-1]<<endl;//why does this have output 4 and 2
//shouldn't it be 1 and i don't know why it[-1] should even work
> but if commented it shows run error
If you could post the code that you have issues with, that would be great.
You are invoking undefined behaviour, the iterators go outside from the valid range. They become invalid, and you shouldn't dereference invalid iterators.
> why it[-1] should even work
because it works with pointers.
Why do we have problem in line 10 why do we need to use iterators to make it work
and the second thing in line 14 if we write it[1] doesn't that meant value at index 1 which is 2 but the output is dif and what does it[-1] that should not work becuase there is no such thing as index -1
What problem are you having on line 10? Could you be more descriptive? Maybe tell us what the error is?
no such thing as index -1
Like ne555 said it[1] and it[-1] work with pointers. C++ allows you to access pointers anywhere in memory as long as your program has permission for that area of memory. So likely subtracting by 1 is not going out of you program's allowed section of memory.
Output:
1,4
4,2
But there is a debug assertion fail
and the expression is:vector iterator not decramental note: the output is interupted
the input is :
Then it likely crashes somewhere after that, since you had a debug assertion fail. This makes me believe you are using some sort of an ide that is running in debug mode to catch these types of logic errors. The logic error is on line 12. You try to go one to the left of the beginning of the array, and then on line 14 you try to dereference that location. Which is an invalid dereference like ne555 has been saying.
Likewise on line 13 you are doing a similar thing by going one to the right of the end location, which is also invalid.
On line 15, I just noticed that you are trying to use [] on iterators. Typically I use the [] operator on the vector itself. http://www.cplusplus.com/reference/vector/vector/operator[]/
Thank you it's alot clear now line 11 produces 4 and 2 which are at index 3 and 1 respectively decrementing and incrementing it should give us index 2 and 0 which should give us an output of 3 and 1 why is it a logic error