C++ auto const&;的类型是什么;映射迭代器?c++;

C++ auto const&;的类型是什么;映射迭代器?c++;,c++,c++11,dictionary,iterator,C++,C++11,Dictionary,Iterator,我需要修复我的一个老项目中的一些bug,我认为这是重构一些代码的最佳时机 我有一张以下结构的地图: std::map< std::string, std::map<std::string, myClass*> > ComponentMap; 我得到了以下编译错误: IsComponentOfType(const std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<

我需要修复我的一个老项目中的一些bug,我认为这是重构一些代码的最佳时机

我有一张以下结构的地图:

std::map< std::string, std::map<std::string, myClass*> > ComponentMap;
我得到了以下编译错误:

IsComponentOfType(const std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const _Kty,_Ty>>>> &,const sCOMPONENT_TYPE &)': cannot convert argument 1 from 'const std::pair<const _Kty,_Ty>' to 'const std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const _Kty,_Ty>>>> &'
IsComponentOfType(const std::_Tree\u iterator&,const scoComponent\u TYPE&):无法将参数1从“const std::pair”转换为“const std::_Tree\u iterator&”
为了“使”c++11语法工作,我需要重写函数的第一个参数的类型是什么

std::map< std::string, std::map<std::string, myClass*> > ComponentMap;
iter
的类型可以有效地推断为
std::map::value\u type const&
,它等于
std::pair const&

iter->second

使用a得到的是而不是迭代器,它是一个值。每个值对应于您循环的容器中的一个元素。

C++11 for loops over elements

备份并返回到工作循环代码。然后添加行
autoconst&elem=*iter位于循环的顶部

接下来,逐行消除循环体中的
iter
。确保代码在更改每一行后编译并运行

if (IsComponentOfType(iter, 
将此更改为

if (IsComponentOfType(elem, 
elem.second
在C++03代码中编译(修改
IsComponentOfType
以获取
std::pair const&

将此更改为

if (IsComponentOfType(elem, 
elem.second
完成后(和其他地方类似),将循环更改为C++11样式:

for (auto const& elem: ComponentMap[compNameString])
完成了。

attr(可选)(范围声明:范围表达式)循环语句

range_声明-命名变量的声明,的类型是range_表达式表示的序列元素的类型,或对该类型的引用。通常使用自动说明符进行自动类型推断

由于
iter
是一个值,
而不是:

iter->second->GetComponentValue(date, compName, 00);
这应该起作用:

iter.second->GetComponentValue(date, compName, 00);

auto const&iter
使用这种语法,它将不是迭代器,而是迭代器指向的对象,iirc是一对常量字符串myClass*。(编辑:事实上,您的错误消息告诉您:
无法将参数1从“const std::pair”
)错误告诉您类型:
const std::pair
\\\
\\\
是映射的键和值模板参数。将迭代器作为函数的参数是糟糕的设计。它应该采用一个值、引用或常量引用。来自OP:“我的问题是:当我重写for循环时:
for(auto-const&iter:ComponentMap[compNameString])
”他们已经按照您的建议做了,这就是为什么他们首先会出错的原因。@Borgleader Yack建议撤消该步骤,先执行其他步骤(包括更改代码< IsComponentOfType > <代码>),并且在这之后,就更改为代码,此时所有的东西都应该工作。这个答案是一个重构配方,它可以使你从点A(旧代码,工作)到B(C++ 11风格,工作)。通过小的中间步骤,所有这些步骤都会产生工作代码。@melpomene-Huh,这对我来说绝对不清楚。@borg澄清。在这种情况下,它不是一个值,而是一个对值的
const
引用。
iter->second->GetComponentValue(date, compName, 00);
iter.second->GetComponentValue(date, compName, 00);