Iterator(of a vector or string) minus n (iter - n) for c++
Some detail description for my question:
- Create an iterator of vector or string in c++ 11.
- Do iterator arithmetic, iterator minus n
Question: Will c++ 11 keep the iterator minus n bigger than begin()? (if n is big enough, will the compiler ensure that the iter - n do not exceed the legal range of iterator?)
Solution 1:
According to cppreference, iter - n
is effectively the same as:
vector<T>::iterator temp = iter;
while(n--) --temp;
return temp;
Assuming iter
was a iterator from a vector
named container
. If n
is larger than distance(container.begin(), iter)
, then at some point from the last while
loop, --temp
would be equivalent of:
--container.begin();
And according to cppreference, that line would be undefined behavior.
Since an iterator cannot know any information of the originated container, it does not have a way to detect if it is currently container.begin()
, thus it cannot ensure it to be remained in the legal range without manually checking against the range.
Solution 2:
It will not, it will simply perform the arithmetic operations and print the values in negative number.
Performed the code using VSCode.
#include<conio.h>
#include<iostream>
#include<vector>
using namespace std;
int main(){
vector<int> v = {1,2,3,4,5,6};
vector<int> :: iterator it;
for(it=v.begin();it!=v.end();it++)
cout<<*it-6<<endl;
return 0;
}
and the results were :
-5
-4
-3
-2
-1
0