简体   繁体   English

将map <> :: iterator传递为map <> :: const_iterator&

[英]Passing map<>::iterator as map<>::const_iterator &

I have a problem passing a map<...>::iterator object to a function as a const_iterator & on GCC: 我在将map <...> :: iterator对象作为const_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"

    }

My probelm is that on Visual Studio 2010 the code above works perfectly fine, but on GCC 4.1.2 I get an error saying there is no matching function to the function call, for _GetInstList(it, SomeString). 我的观点是,在Visual Studio 2010上,上面的代码可以很好地工作,但是在GCC 4.1.2上,我收到一条错误消息,指出针对_GetInstList(it,SomeString)的函数调用没有匹配的函数。 The issue seems to be converting iterator to const_iterator &. 问题似乎是将迭代器转换为const_iterator&。

I have to take it by reference because "it" gets changed inside _GetInstList() and the caller function checks it. 我必须引用它,因为_GetInstList()内部的“ it”已更改,并且调用方函数会对其进行检查。 (The "it" pointer is changed not a pointed element). (“ it”指针更改为非指针元素)。

Also, the "it" in SomeFunction() cannot be const because it changes an element. 另外,SomeFunction()中的“ it”不能为const,因为它更改了元素。

How can I resolve this? 我该如何解决?

EDIT: For those who suggest that the problem is the conversion from iterator to const_iterator: The code compiles fine if the function prototype is changed to take const_iterator NOT as a reference, the problem is the const &. 编辑:对于那些建议问题是从迭代器到const_iterator的转换的人:如果将函数原型更改为采用const_iterator NOT作为参考,则代码可以正常编译,问题是const&。

Change your argument type to const map<string,InstList>::const_iterator& or just a map<string,InstList>::const_iterator . 将您的参数类型更改为const map<string,InstList>::const_iterator&或只是map<string,InstList>::const_iterator

Here's an example demonstrating your problem (and the solution) with simple types: 这是一个使用简单类型演示您的问题(和解决方案)的示例:

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
}

I think maybe this method should be redesigned anyway. 我认为也许应该重新设计此方法。 Passing iterators around is messy and confusing for others to read. 传递迭代器很麻烦,其他人也难以理解。 How hard would it be to do that? 这样做有多难?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM