Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easier C++ STL iterator instantiation

Tags:

c++

stl

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;
like image 893
Waslap Avatar asked Oct 11 '14 06:10

Waslap


4 Answers

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;
like image 117
P0W Avatar answered Nov 20 '22 14:11

P0W


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.

like image 23
Tom Avatar answered Nov 20 '22 15:11

Tom


In C++11 you can write:

decltype(v)::iterator
like image 2
M.M Avatar answered Nov 20 '22 15:11

M.M


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';
like image 2
Galik Avatar answered Nov 20 '22 15:11

Galik