Search code examples
c++iterator

Iterators in C++. How to modify a vector knowing its iterators?


Trying to understand iterators in C++. For example, in the code below we print a vector.

using Iterator = vector<int>::iterator;

void PrintRange(Iterator range_begin, Iterator range_end) {
    for (auto it = range_begin; it != range_end; ++it) {
        cout << *it << " ";
    }
}

int main() {
    vector<int> numbers = {5, 3, 2, 1};
    PrintRange(begin(numbers), end(numbers));
    return 0;
}
// 5 3 2 1 

My question is how to properly write a function that takes only two iterators and that modifies the vector. For example, the function my_sort sorts a vector and if we write

my_sort(begin(numbers), end(numbers));

number contains a modified sorted vector.

void my_sort(Iterator range_begin, Iterator range_end) {
    // how to modify a vector knowing its iterators ?
}

Solution

  • How to modify a vector knowing its iterators?

    You can indirect through an input iterator to access the element that it points to. Example:

    auto it = std::begin(numbers);
    *it = 42;
    

    For example, the function my_sort sorts a vector

    A sorting function generally swaps elements around. You can swap to elements pointed by iterators like this:

    std::iter_swap(it1, it2);