0

I have a question regarding the iterators, last iterator is pointer to element 3 if exists, and if it is not incremented and I use assign why the range is 1,2 and 3 is not included ?

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

const std::vector<uint32_t> vec = {1, 2, 3, 4, 5};




int main()
{
    auto first = std::find(vec.begin(), vec.end(), 1);
    auto last = std::find(vec.begin(), vec.end(), 3);
    std::cout<< "last: " << *last << std::endl << std::endl;
    // last: 3
    
    std::vector<int> v;
    // last ++;
    v.assign(first, last);
    
    for (const int i: v)
    {
        std::cout<<i<< " ";
    }
    
    // 1 2 
    // last ++; ===> 1 2 3
    
    return 0;
}
  • 4
    An `end` iterator typically points to "one after the last element". So the element pointed to is not included. – super May 29 '22 at 09:11
  • C++ templates usually express ranges as a half-open range `[begin, end)` which is **exclusive** of the ending. A range that is `[x, x)` where the begin and end are the same signifies an *empty* range. – Eljay May 29 '22 at 11:48

0 Answers0