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).
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";
}
CodePudding user response:
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;
.