Reputation: 10153
I found in a post how to delete elements from a container using an iterator. While iterating:
for(auto it = translationEvents.begin(); it != translationEvents.end();)
{
auto next = it;
++next; // get the next element
it->second(this); // process (and maybe delete) the current element
it = next; // skip to the next element
}
Why is auto
used without the type in auto next = it;
?
I use VS10,not C++11 !
Upvotes: 10
Views: 24098
Reputation: 110768
auto
has a different meaning in C++11 than it did before. In earlier standards, auto
was a storage specifier for automatic storage duration - the typical storage an object has where it is destroyed at the end of its scope. In C++11, the auto
keyword is used for type deduction of variables. The type of the variable is deduced from the expression being used to initialise it, much in the same way template parameters may be deduced from the types of a template function's arguments.
This type deduction is useful when typing out ugly long types has no benefit. Often, the type is obvious from the initialiser. It is also useful for variables whose type might depend on which instantiation of a template it appears in.
Many C++11 features are supported by default in VC10 and auto
is one of them.
Upvotes: 18
Reputation: 74108
This is called type inference. The type of the auto variable is deduced by the type of the initializer.
E.g., this reduces the amount to type for large and complicated template types.
Upvotes: 3
Reputation: 6409
It's called Type Inference, see also this question for details. New in C++11, and intended to simplify many long and unnecessary codes, especially for iterators and function bindings.
Upvotes: 4
Reputation: 4983
It is a short-hand in newer versions of C++ that allows us to avoid the clunky iterator notation, since the compiler is able to infer what the actual type is supposed to be.
Upvotes: 5