C++ 通行图<>;::迭代器作为映射<>;::常量迭代器&;

C++ 通行图<>;::迭代器作为映射<>;::常量迭代器&;,c++,map,stl,iterator,const-iterator,C++,Map,Stl,Iterator,Const Iterator,我在将map::iterator对象作为常量迭代器传递给函数时遇到问题&GCC: class MyClass { }; bool MyClass::_GetInstList(map<string,InstList>::const_iterator & it, const string & sMod) { cout<<"Matched\n"; it = tInstancesData.find(sMod); if( it == t

我在将map::iterator对象作为常量迭代器传递给函数时遇到问题&GCC:

class MyClass {


};

bool MyClass::_GetInstList(map<string,InstList>::const_iterator & it, const string & sMod)
{
    cout<<"Matched\n";
    it = tInstancesData.find(sMod);
    if( it == tInstancesData.end() ) {
        cout<<"\""<<sMod<<"\" is NOT a module\n";
        return false;
    }
    return true;
}

    bool SomeFunction()
    {

            map<string,InstList>::iterator  it;
            if( ! _GetInstList(it, SomeString) ) return false;
            it->second.Add(...);  //  Modifying element pointed by "it"

    }
class-MyClass{
};
boolmyclass::\u GetInstList(map::const\u迭代器和it、const字符串和sMod)
{

cout我认为可能无论如何都应该重新设计这个方法。传递迭代器对于其他人来说是混乱和混乱的。这样做有多困难?

将参数类型更改为
const-map::const\u迭代器&
或只是一个
map::const\u迭代器

下面是一个用简单类型演示您的问题(和解决方案)的示例:

void func1(double& x){}
void func2(const double& x){}

int main()
{
    int x;
    func1(x); // error: 'func1' : cannot convert parameter 1 from 'int' to 'double &'
    func2(x); // succeeds
}

在调用之前转换为常量迭代器?或者首先从常量迭代器开始?或者使代码通用并接受任何迭代器。为什么
\u GetInstList()
需要一个
常量迭代器
?标准规定
迭代器
可以转换为
常量迭代器
。标准并没有说
迭代器
常量迭代器
,因此该迭代器不适用于对它的引用。它不继承自它的常量对应项,因此它是一个需要c的转换ast.@R.MartinhoFernandes-我已经这样做了,但仍然得到了相同的错误。我首先需要它作为一个非常量迭代器,正如在文章中提到的。我将更改您的
\u GetInstList
以不接受迭代器参数,只需返回一对
bool
true
如果找到)和一个非常量迭代器(如果找到则有效)。这不是更有意义吗?你建议用什么来代替迭代器?对象本身?不管怎样,我认为在函数参数中使用迭代器并不能为其他人提供一个干净的、可重用的接口。仅凭我的意见。对象本身不能移动到以下对象。整个STL使用迭代器对s表示函数(std::acculate、std::copy、std::remove等),所以说“传递迭代器很麻烦”与STL的设计选择相矛盾。