翻译C++代码片段



我正在将一个框架从C++移植到Java,结果比我预期的要困难,因为我对C++了解不多。我偶然发现了一个我不太理解的片段。如果有人能告诉我标记的线是干什么的,那就太棒了。

  /** 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);
    }
  }

insert成员函数返回一对,如果进行了插入,则其bool组件返回true;如果映射已包含关键字在排序中具有等效值的元素,则其返回false;其迭代器组件返回插入新元素或元素已位于的地址。

因此,该代码将向map添加一个元素,如果该元素还没有出现,则会将数据推送到vector中。

此处使用的insert成员函数返回一个pair<iterator, bool>,其中如果进行了插入,则bool成员为true。因此,if语句查看insert调用是否真的向映射添加了一条记录。

使用C++时,您可能会发现参考标准库的文档很有用——以下是map::insert上的MSDN页面。

最新更新