C++ ITERATOR

Any object that can iterate through the contents of a range of elements (such as an array or container) using a set of operators, including at least the increment (++) and dereference (*) operators, is referred to as an iterator.

The memory locations of STL containers are pointed at using iterators. They are generally employed in series of numbers, letters, or other symbols.

You use the syntax to ask for an iterator suitable for a specific STL templated class.

For instance, you might make an iterator for an STL vector holding integers by doing the following:

There are many functions used to perform different operations on operators.

The beginning point of the container is returned by the begin() method. end() This method is used to return the container's after end position. next() gives the new iterator to which the current iterator would point after moving through the places specified in its parameters. prev() This method returns the new iterator to which the existing iterator would point once the locations specified in its arguments have been decreased.

Code:



    #include "iostream"
    #include "iterator" // for iterators
    #include "vector" // for vectors
    using namespace std;

    int main()
    {

      vector ar = { 1, 2, 3, 4, 5 };

      // Declaring iterators to a vector
      vector::iterator ptr = ar.begin();
      vector::iterator ftr = ar.end();
      // Using next() to return new iterator
      // points to 4
      auto it = next(ptr, 3);// Using prev() to return new iterator
      // points to 3
      auto it1 = prev(ftr, 3);
      // Displaying iterator position
      cout << "The position of new iterator using next() is : ";
      cout << *it << " ";
      cout << endl;
      // Displaying iterator position
      cout << "The position of new iterator using prev() is : ";
      cout << *it1 << " ";
      cout << endl;
      return 0;
            }

Output:


The position of new iterator using next() is : 4
The position of new iterator using prev() is : 3





© Copyright 2022 Advanced PLC. All rights reserved.