【问题标题】:translating C++ snippet翻译 C++ 片段
【发布时间】:2011-09-30 01:20:37
【问题描述】:

我正在努力将一个框架从 C++ 移植到 Java,结果比我预期的要难,因为我对 C++ 知之甚少。我遇到了这个我不太了解的sn-p。如果有人能告诉我标记的行是做什么的,那就太棒了。

  /** Heap data, stored as a vector */
  std::vector< std::pair< _Tp, _Val > > data;

  /** Maps objects to their positions in the data vector */
  std::map< _Tp, int> mapping;


  //I understand that this method takes a pair of type <_Tp, _Val>
  template <class _Tp, class _Val>
  void Heap<_Tp,_Val>::push(std::pair< _Tp, _Val > x)
  {
    int index=data.size();

    //Here is where I run into trouble
    //I can't seem to figure out what this line is doing
    //I know it is inserting a Key-Value pair into the map
    //but why is .second being called? and what exactly is this if statement
    //checking?
    if (mapping.insert(std::make_pair(x.first,index)).second)
    {
      data.push_back(x);
      percolate_up(index);
    }
  }

【问题讨论】:

    标签: c++


    【解决方案1】:

    insert 成员函数返回一个对,其 bool 组件在插入时返回 true,如果映射已经包含一个元素,其键在排序中具有等效值,并且其迭代器组件返回地址插入新元素的位置或元素已位于的位置。

    因此,该代码正在向map 添加一个元素,如果该元素不存在,它会将数据推送到vector

    【讨论】:

    • 哦,好的,谢谢。我正在查看的页面没有列出一对返回值..lame。对于我从中获取信息的网站,我必须更加小心。谢谢
    • @Hunter - 返回一对不是“标准”行为。我想你正在使用VC++?!依靠对返回的向量插入是不可移植的。因此,您查看的页面可能没有错,只是与您的编译器不匹配。
    • @Michael:不是vector insert而是map insert,而且pair return在C++11标准中有,这在C++03中是不是无效?
    • @K-ballo - 抱歉,是指地图。我不是语言律师,但我不认为 C++03 标准定义了一对的返回。过去从 Win 上的 VC++ 到 *nix 上的 gcc,我遇到过这个问题。有关 void 返回的示例,请参阅 here
    【解决方案2】:

    这里使用的insert 成员函数返回一个pair&lt;iterator, bool&gt;,如果进行了插入,则bool 成员是true。因此,if 语句是查看 insert 调用是否实际上向地图添加了一条记录。

    您可能会发现在使用 C++ 时参考标准库的文档很有用 - here's the MSDN page on map::insert

    【讨论】:

    • 感谢您的评论,我没有看到我正在查看的页面上列出的返回类型。另外,谢谢你的链接
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-17
    相关资源
    最近更新 更多