Home > Net >  subtraction of iterators that give integer number
subtraction of iterators that give integer number

Time:10-08

can someone tell me what happens under in this subtraction?
why did I get a number in the end? its build operator '-' or something else?

int main(){
    
    vector<int> v{5,3,8,3,9};
    auto p=remove(begin(v),end(v),3);
   
    cout<<p-begin(v);
   
    return 0;
}

output: 3

CodePudding user response:

Iterators for std::vector are LegacyRandomAccessIterators, and you can see in that link that subtracting one such iterator from another yields a difference_type. For std::vector, this is defined as "a signed integer type (usually std::ptrdiff_t)", which sounds like what you wanted.

And yes, the magic occurs inside operator-() (for the iterator).

  • Related