我在一篇文章中发现了如何使用迭代器从容器中删除元素.在迭代时:
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
}
Run Code Online (Sandbox Code Playgroud)
为什么auto没有使用类型auto next = it;?
我使用的是VS10,而不是C++ 11!
Jos*_*eld 14
auto在C++ 11中具有与以前不同的含义.在早期标准中,auto是自动存储持续时间的存储说明符 - 对象在其范围结束时被销毁的典型存储.在C++ 11中,auto关键字用于变量的类型推导.变量的类型是从用于初始化它的表达式推导出来的,就像模板参数可以从模板函数的参数类型推导出来一样.
当输入丑陋的长类型没有任何好处时,这种类型推导很有用.通常,类型从初始化器中显而易见.它对于类型可能取决于它出现在哪个模板实例化的变量也很有用.
VC10默认支持许多C++ 11功能,并且auto是其中之一.