c++ - 翻译 C++ 片段

标签 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);
    }
  }

最佳答案

The insert member function returns a pair whose bool component returns true if an insertion was made and false if the map already contained an element whose key had an equivalent value in the ordering, and whose iterator component returns the address where a new element was inserted or where the element was already located.

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

关于c++ - 翻译 C++ 片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7605056/

相关文章:

c++ - 编译 clang-llvm 示例

c++ - C++如何与操作系统交互?

c++ - 为什么我的#includes 的顺序很重要? (C++)

c++ - 获取 vector 中所有元素的某个组件

C++ 如何从 std::string 中删除\0 字符

python - 为 Ubuntu 发布

c++ - 如何在可能不存在的目录中创建文件?

c++ - 模板生成一百个C回调函数,编译不慢

c++ - 将视频分成场景(片段)的最佳方法是什么

c++ - 基于类实现功能困难