0

I am unable to compile the following program. I am using g++ version 5 on ubuntu.

#include<iostream>
#include<iterator>
int main()
{
    iterator it;
    return 0;
}

It gives me the following errors,

a.cc: In function ‘int main()’:
a.cc:5:5: error: ‘iterator’ was not declared in this scope
     iterator it;
     ^
a.cc:5:5: note: suggested alternatives:
In file included from /usr/include/c++/5/bits/stl_algobase.h:65:0,
                 from /usr/include/c++/5/bits/char_traits.h:39,
                 from /usr/include/c++/5/ios:40,
                 from /usr/include/c++/5/ostream:38,
                 from /usr/include/c++/5/iostream:39,
                 from a.cc:1:
/usr/include/c++/5/bits/stl_iterator_base_types.h:118:12: note:   ‘std::iterator’
     struct iterator
            ^
/usr/include/c++/5/bits/stl_iterator_base_types.h:118:12: note:   ‘std::iterator’
rahul
  • 6,447
  • 3
  • 31
  • 42

1 Answers1

-2

An iterator is an object that points to elements inside a specific container. There is no global iterator type (which is why you got the compiler error). Instead the standard containers, e.g. vector<int> in my example below, define each their own iterator types. The iterator is usually initialized by calling a member function of the container instance over whose elements one wants to iterate. You can think of an iterator as a sophisticated pointer.

You can use built-in functions of a vector to obtain special values of an iterator, such as begin() and end(), which allow you to iterate over all elements it holds.

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    // Declaring a vector
    vector<int> v = { 1, 2, 3 };

    // Declaring an iterator
    vector<int>::iterator i;

    // Accessing the elements through iterators
    // using functions from vector<int>
    for (i = v.begin(); i != v.end(); ++i)
    {
        cout << *i << " ";
    }
}
Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62
Trishant Pahwa
  • 2,559
  • 2
  • 14
  • 31