Search code examples
c++iteratoroperators

subtraction of iterators that give integer number


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


Solution

  • 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).