【问题标题】:C2784 using a set of iterators over mapC2784 在 map 上使用一组迭代器
【发布时间】:2011-09-05 15:37:58
【问题描述】:

以下代码产生编译器错误 C2784:

'bool std::operator &,const std::_Tree<_traits> &)' : 无法推导出 'const std::_Tree<_traits> &' 的模板参数来自'const std::_Tree_iterator<_mytree>'

代码有什么问题?提前谢谢了;我在该错误消息中找不到任何对我有帮助的帖子。

#include <map>
#include <set>

void main(){
int i=1;
     std::map<int, int> A;
A[i]=i;
std::set<std::map<int, int>::iterator > setOfIts;
setOfIts.insert(A.begin());
}

【问题讨论】:

    标签: templates iterator arguments


    【解决方案1】:

    您所看到的是 Visual Studio 长期抱怨它无法比较您想要放置在集合中的迭代器,因为没有合适的 operator &lt;。而且由于它不能比较它们,它不能确定两个迭代器是否具有相同的值,因此应该只有其中一个在集合中。

    要解决此问题,您可以提供自己的小于运算符 - see example here。迭代器相等的含义是什么由你来弄清楚......

    【讨论】:

    • 非常感谢 Eran,它帮助我修复了代码(见下文)。 #include &lt;map&gt; #include &lt;set&gt; typedef std::map&lt;int, int&gt; aMap; typedef aMap::iterator aMapIterator; struct CompareIterators{ bool operator() (const aMapIterator&amp; a, const aMapIterator&amp; b){ return( a-&gt;first &lt; b-&gt;first ); }; }; void main(){ int i=1; aMap A; A[i]=i; std::set&lt;aMapIterator, CompareIterators&gt; setOfIts; setOfIts.insert(A.begin()); }
    • 另一件(自然的)事情——使用这种比较迭代器的实现,必须非常小心,稍后在setOfOts 中插入的迭代器实际上将指向aMap 的元素。否则代码仍会编译,但不会运行。
    猜你喜欢
    • 2017-10-08
    • 2018-01-19
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    相关资源
    最近更新 更多