【发布时间】:2018-08-28 11:49:01
【问题描述】:
我需要修复我的一个旧项目的一些错误,我认为这是重构一些代码的最佳时机。
我有以下结构的地图:
std::map< std::string, std::map<std::string, myClass*> > ComponentMap;
某处我需要遍历一些底层子地图,我使用了以下内容:
for (std::map<std::string, myClass* >::iterator iter = ComponentMap[compNameString].begin(); iter != ComponentMap[compNameString].end(); ++iter)
{
//some code
if (IsComponentOfType(iter, sCOMP_PRINCIPAL))
iter->second->GetComponentValue(date, compName, 00);
//some more code
}
IsComponentOfType 函数具有以下声明:
bool IsComponentOfType(const std::map<std::string, myClass* >::iterator & MapIter, const sCOMPONENT_TYPE & Type)
我的问题是: 当我这样重写for循环时:
for (auto const& iter: ComponentMap[compNameString])
我收到以下编译错误:
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>>>> &'
为了“使”c++11 语法起作用,我需要重写函数的第一个参数是什么类型的?
【问题讨论】:
-
auto const& iter使用该语法它不会是迭代器,它将是迭代器指向的内容,iirc 是一对 const 字符串 myClass*。 (编辑:事实上你的错误信息告诉你:cannot convert argument 1 from 'const std::pair<const _Kty,_Ty>') -
错误告诉你类型:
const std::pair<const _Kty,_Ty>。_Kty和_Ty是映射的键和值模板参数。 -
将迭代器作为函数的参数是糟糕的设计。它应该采用值、引用或常量引用。
标签: c++ c++11 dictionary iterator