Search code examples
c++boostcontainersboost-iterators

Efficient way to refer to the type-name of the iterator without typing the entire container definition?


Is there a more efficient way to refer to the typename of a container's iterator than typing

std::unordered_map<keyclass, valueclass>::iterator 

every time I need the iterator?

Of course, there is

typedef boost::unordered_map<keyclass, valueclass>::iterator classitr

but introducing typedef's for every container does not strike me as very readable code. Being new to C++, and assuming that one usually has a reference to the container they want to use - is there something along the lines of

Container<KeyClass, ValueClass> x;

x::iterator_type i

or any other obvious shortcut that I am missing?


Solution

  • This is one of the reasons why C++11 introduced the new meaning of the auto keyword:

    auto it = vec.begin();
    

    The compiler will work out the type of it from the initializer in a similar manner to template type deduction.

    Pre-C++11, the usual approach was to use typedefs as you have suggested. It can often be most useful to typedef the container and then give everything relative to that:

    typedef std::unordered_map<key, value> map;
    map m;
    map::iterator = m.begin();
    

    You can give a more meaningful name to your typedef that describes exactly what kind of map it is. For example, if you had a map from names to phone numbers, you could call it phone_map and the iterator would be phone_map::iterator.

    auto is also a useful tool for perfect forwarding