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 !
In computer programming, an automatic variable is a local variable which is allocated and deallocated automatically when program flow enters and leaves the variable's scope. The scope is the lexical context, particularly the function or block in which a variable is defined.
The auto keyword is a simple way to declare a variable that has a complicated type. For example, you can use auto to declare a variable where the initialization expression involves templates, pointers to functions, or pointers to members.
The variables which are declared inside a block are known as automatic or local variables; these variables allocates memory automatically upon entry to that block and free the occupied memory upon exit from that block.
The auto keyword can not only be used as the return type for functions but also as the data type of the parameters declared in the function.
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.
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.
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.
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