Easy STL STL Iterator Creation

Is there a way to syntactically shorten / simplify iterator declarations in C ++. Normally I would:

vector<pair<string, int> > v; vector<pair<string, int> >::iterator i; 

I was hoping for magic that:

 vector<pair<string, int> > v; magic v::iterator i; 
+6
source share
5 answers

In C ++ 11, you have three options:

1. Typedef vector instance

 typedef std::vector<std::pair<std::string, int>> Vp; Vp v; Vp::iterator i; 

2. Use decltype

 std::vector<std::pair<std::string, int>> v; decltype(v)::iterator i; 

3. Use auto

 std::vector<std::pair<std::string, int>> v; auto i = v.begin(); 

I would say that the third option is the most common, idiomatic use, but they are all valid, and the first option also works in C ++ 98.

+5
source

Just use typedef to smooth your vector<pair<string, int> >

 typedef vector<pair<string, int> > Vp; // vector of pair 

And then,

 Vp v; Vp::iterator i; 
+7
source

I use typedefs a lot:

 // vector of strings typedef std::vector<std::string> str_vec; // iterator typedef str_vec::iterator str_vec_iter; // constant iterator typedef str_vec::const_iterator str_vec_citer; // reverse iterator typedef str_vec::reverse_iterator str_vec_riter; // constant reverse iterator typedef str_vec::const_reverse_iterator str_vec_criter int main() { str_vec v = {"a", "b", "c"}; // writable iteration for(str_vec_iter i = v.begin(); i != v.end(); ++i) i->append("!"); // constant iteration for(str_vec_citer i = v.begin(); i != v.end(); ++i) std::cout << *i << '\n'; // constant reverse iteration for(str_vec_criter i = v.rbegin(); i != v.rend(); ++i) std::cout << *i << '\n'; } 

Some containers are so common that I have their typedefs in personal header files that I use all the time (naturally, names).

But since C ++ 11 is not so important because of the auto keyword, which prints a type for you:

 for(auto&& i: v) std::cout << i << '\n'; 
+2
source

In C ++ 11 you can write:

 decltype(v)::iterator 
+2
source

C ++ 11:

 using v = vector<pair<string, int> >; using i = v::iterator; 

Magic:

 v _v; i _i{ _v.begin( ) }; 
0
source

Source: https://habr.com/ru/post/976599/


All Articles