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 some magic that would:
vector<pair<string, int> > v;
magic v::iterator i;
Simply use typedef
for aliasing your vector<pair<string, int> >
typedef vector<pair<string, int> > Vp; // vector of pair
And then,
Vp v;
Vp::iterator i;
In C++11, you have three options:
1. Typedef the vector instantiation
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'd say the third option is the most common, idiomatic usage, but all are valid, and the first option works in C++98, too.
In C++11 you can write:
decltype(v)::iterator
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';
}
Certain containers are so common that I have their typedefs in personal header files that I use all the time (namespaced naturally).
But since C++11 its not so important because of the auto
keyword that deduces the type for you:
for(auto&& i: v)
std::cout << i << '\n';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With