Home > Back-end >  Using iterators but with same amount of loc?
Using iterators but with same amount of loc?

Time:10-06

One can loop over a list by both:

#include <iostream>
#include <list>

using namespace std;

int main()
{
    list<int> alist{1, 2, 3};

    for (const auto& i : alist)
        cout << i << endl;

    list<int>::iterator i;
    for (i = alist.begin(); i != alist.end(); i  )
        cout << *i << endl;

    return 0;
}

Mostly I don't use iterators because of the extra line of code I have to write, list<int>::iterator i;.

Is there anyway of not writing it? And still use iterator? Any new trick on newer C versions? Perhaps implementing my own list instead of using the one from stl?

CodePudding user response:

Mostly I don't use iterators because of the extra line of code I have to write, list<int>::iterator i;.

You don't need to put it in an extra line. As with every for loop, you can define the iterator type inside of the parentheses, unless you'll need the value outside of the loops body.

So you can also write

    for (list<int>::iterator i = alist.begin(); i != alist.end(); i  )
        cout << *i << endl;

or

    for (auto i = alist.begin(); i != alist.end(); i  )
        cout << *i << endl;
  • Related