【问题标题】:C++ Pass entire list by referenceC++ 通过引用传递整个列表
【发布时间】:2013-05-30 19:27:59
【问题描述】:

我有以下代码:

void endConditionalFlowsBetweenSets(const list<unsigned int>& sourceSet, const     list<unsigned int>& endSet){
    //TODO: Optimize
    //ending previous flows between the two sets
    list<unsigned int>::iterator itS;
    list<unsigned int>::iterator itE;
    for(itS=sourceSet.begin();itS!=sourceSet.end();itS++)
        for(itE=endSet.begin();itE!=endSet.end();itE++)
            if(*itS!=*itE && linkIndex[*itS][*itE].index==-1)   
                endFlow(*itS,*itE);
}

编译时出现错误:no known conversion for argument 1 from ‘std::list&lt;unsigned int&gt;::const_iterator {aka std::_List_const_iterator&lt;unsigned int&gt;}’ to ‘const std::_List_iterator&lt;unsigned int&gt;&amp;’

这是为什么呢?我只是通过引用传递一个列表并创建一个迭代器来迭代它。

【问题讨论】:

  • 迭代器也需要是const

标签: c++ list pass-by-reference


【解决方案1】:

你应该使用const_iterator:

 list<unsigned int>::const_iterator itS;
 list<unsigned int>::const_iterator itE;

【讨论】:

    【解决方案2】:

    我只是通过引用传递一个列表

    不,您通过 const 引用传递它。您的参数和迭代器之间存在const 不匹配。

    要么更改函数签名:

    void endConditionalFlowsBetweenSets(
        list<unsigned int>& sourceSet,
        list<unsigned int>& endSet);
    

    或更改迭代器声明:

     list<unsigned int>::const_iterator itS;
     list<unsigned int>::const_iterator itE;
    

    【讨论】:

    • 谢谢大家!问题已解决
    • 请投票(单击向上的三角形)对您有帮助的答案,并接受(单击复选标记)其中一个。
    【解决方案3】:

    您的列表 sourceSet 是 const,但您正在尝试创建非 const 迭代器。如果你能做到这一点,你就可以修改列表,这不好,因为列表是const

    这就是为什么你应该使用list&lt;unsigned int&gt;::const_iterator

    【讨论】:

      【解决方案4】:

      你需要使用const_iterator:

      list<unsigned int>::const_iterator itS;
      list<unsigned int>::const_iterator itE;
      

      您将sourceSet 作为const 传递,因此您不能使用非const 迭代器。

      【讨论】:

        【解决方案5】:

        如果你只使用auto 并让编译器找到合适的类型,这整个问题就不会发生:

        for(auto itS=sourceSet.begin(); itS!=sourceSet.end(); itS++)
            for(auto itE=endSet.begin(); itE!=endSet.end(); itE++)
                if(*itS!=*itE && linkIndex[*itS][*itE].index==-1)   
                    endFlow(*itS,*itE);
        

        你也可以考虑for循环的范围

        for(auto src : sourceSet)   // src is unsigned int
            for(auto&end : endSet)  // end is unsigned int&  allows manipulation in endFlow
                if(src != end && linkIndex[src][end].index==-1)
                   endFlow(src,end);
        

        【讨论】:

          猜你喜欢
          • 2014-10-13
          • 2010-12-31
          • 1970-01-01
          • 2011-01-17
          • 2021-08-15
          • 2018-06-29
          • 2020-04-01
          • 2014-03-10
          • 2012-06-14
          相关资源
          最近更新 更多