Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using iterators but with same amount of loc?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading