Home > Software design >  Iterator(of a vector or string) minus n (iter - n) for c
Iterator(of a vector or string) minus n (iter - n) for c

Time:01-15

Some detail description for my question:

  1. Create an iterator of vector or string in c 11.
  2. 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?)

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

It will not! I wrote following code, then the VS2019 reported "degug assert failed"!

std::vector<int> v1 = { 1,2,3,4,5,6,7 };
std::vector<int> v_assign;
v_assign.assign(v1.begin() - 2, v1.begin()   3);

CodePudding user response:

No, iterator arithmetic will not do any bounds checking on the result. You can easily end up with an invalid iterator.

A random access iterator such as given by std::vector will allow you to do subtraction, so you can impose your own bounds checking.

it2 = it - min(n, it - container.begin());
  •  Tags:  
  • Related