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

What is the correct way of declaring an iterator?

I am wondering if there is any difference between using

std::set<int,std::greater<int>>::iterator itr;

and

std::set<int>::iterator itr;

I tried the two of them in the code below and the result is the same, I would like know is there is any difference between one and the other or if there is any instance in which I should need to use one over the other (when using the STL library or another case).

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

CODE:

#include<iostream>
#include<iterator>
#include<set>

int main(){
    std::set<int,std::greater<int>> s1;
    s1.insert(40);
    s1.insert(30);
    s1.insert(60);
    s1.insert(20);
    s1.insert(50);
    s1.insert(10);
    // std::set<int>::iterator itr;
    std::set<int,std::greater<int>>::iterator itr;
    std::cout<<"\nThe set s1 is: \n";
    for(itr=s1.begin();itr!=s1.end();itr++){
        std::cout<<*itr<<" ";
    }
    std::cout<<"\n";
}

>Solution :

std::set<int>::iterator itr; is wrong.

It happens to work on both GCC, Clang, and MSVC by default.
But e.g. if I enable GCC’s iterator debugging (-D_GLIBCXX_DEBUG), it stops compiling.

Normally you don’t need to manually spell the iterator type. You can do for (auto itr = s1.begin(); ...). Or, if the iterator needs to be created uninitialized, decltype(s1)::iterator itr;.

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