arithmetic operations on iterator

Let it is an iterator.

it+1 or it-x I mean arithmetic increment or decrement does NOT work for iterators of sets or multisets. You have to use ++it or - -it. You know how post in/decrement and pre in/decrement works, right? So they modifies the original it iterator.

set <int> :: iterator it = it+3; //won't work

The ability to use the + operator with iterators depends on the category of the iterator.

  1. Random Access Iterators:
#include <iostream>#include <vector>int main() {
    std::vector<int> myVector = {1, 2, 3, 4, 5};
    auto it = myVector.begin() + 2; // Advance iterator by 2 positions

    std::cout << "Value: " << *it << std::endl;

    return 0;
}

  1. Bidirectional and Forward Iterators:

    cppCopy code
    #include <iostream>#include <list>#include <iterator>int main() {
        std::list<int> myList = {1, 2, 3, 4, 5};
        auto it = std::next(myList.begin(), 2); // Advance iterator by 2 positions
    
        std::cout << "Value: " << *it << std::endl;
    
        return 0;
    }
    
    

Alternatively, you can use next(), prev() and advance().

https://lh3.googleusercontent.com/a/AEdFTp6wkPf-TZrak2mhDBlFKcKf3oQYcPRMLw2TU3UOpA=s96-c

how does next() and prev() work? does it itself advance or backword the iterator?.

  1. std::next():

    Example:

    cppCopy code
    #include <iostream>#include <iterator>int main() {
        std::set<int> mySet = {1, 2, 3, 4, 5};
        auto it = mySet.begin();
    
        auto nextIterator = std::next(it, 2);
    
        std::cout << "Current: " << *it << std::endl;
        std::cout << "Next (2 positions ahead): " << *nextIterator << std::endl;
    
        return 0;
    }
    
  2. std::prev():

    Example:

    cppCopy code
    #include <iostream>#include <iterator>int main() {
        std::set<int> mySet = {1, 2, 3, 4, 5};
        auto it = mySet.end();  // pointing to the imaginary "past-the-end" element
    
        auto prevIterator = std::prev(it, 2);
    
        std::cout << "Current: " << *it << std::endl;
        std::cout << "Previous (2 positions before): " << *prevIterator << std::endl;
    
        return 0;
    }
    
    

It's essential to be cautious and make sure that the resulting iterator is valid for the container in use. If the operation would go out of bounds, you might encounter undefined behavior.

https://lh3.googleusercontent.com/a/AEdFTp6wkPf-TZrak2mhDBlFKcKf3oQYcPRMLw2TU3UOpA=s96-c

does advance() modify the original iterator?

Yes, the std::advance() function modifies the original iterator. It moves the iterator forward or backward by a specified number of positions and updates the original iterator to point to the new position.


int main() {
    std::set<int> mySet = {1, 2, 3, 4, 5};
    auto it = mySet.begin();

    // Advance the iterator by 2 positions
    std::advance(it, 2);

    // Print the value at the new position
    std::cout << "Value after advancing: " << *it << std::endl;

    return 0;
}