【问题标题】:std::map with an object as value以对象为值的 std::map
【发布时间】:2013-04-22 19:29:58
【问题描述】:

我在尝试将 std::map 与我自己的类用作值时出错。地图的定义是这样的:

 std::map<std::string,CCrossSection> Xsects;

这一行编译得很好(所以它有点工作?)

Xsects[sectionId].m_vProfile.push_back(pt);

当我尝试迭代地图时:

for (std::map<std::string,CCrossSection>::iterator xs = Xsects.begin(); xs < Xsects.end(); xs++) {
    it->second.SaveFile(f);
}

它给了我多个类似这样的错误:

error C2784: 'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' : could not deduce template argument for 'const std::_Tree<_Traits> &' from 'std::_Tree<_Traits>::iterator'
        with
        [
           _Traits=std::_Tmap_traits<std::string,CCrossSection,std::less<std::string>,std::allocator<std::pair<const std::string,CCrossSection>>,false>
        ]
        c:\program files\microsoft visual studio 9.0\vc\include\xtree(1466) : see declaration of 'std::operator <'

我认为这是 less 运算符的问题,我将它添加到我的 CCrossSection 类的定义中,但它并没有改变任何事情。后来我读到地图的键必须定义较少的运算符,我认为 std::string 有。任何想法为什么会发生?

干杯 托梅克

【问题讨论】:

标签: c++ stl


【解决方案1】:

当您将结束迭代器与运算符进行比较时,它将编译!=

【讨论】:

  • :- 你是对的。但是在这里我有一个问题,为什么map 不适用于&lt;
  • 在任何迭代器的末尾递增是未定义的行为,请查看stackoverflow.com/questions/6673762/why-is-used-with-iterators
  • nop map 不起作用,iterator 不适用于 operator&lt;()
  • 与向量不同,地图不一定将其在内存中的对象从低到高排序,因此运算符
  • 准确答案:operator&lt; 适用于随机访问迭代器。这些也支持operator+operator-,而iterA&lt;iterB 仅表示iterA-iterB &lt; 0。但是,map 只有双向迭代器。他们支持operator++,但不支持operator+
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-30
  • 1970-01-01
  • 2014-12-16
相关资源
最近更新 更多