2011-09-30 189 views
4

我正致力于将一个框架从C++移植到Java,并且事实证明比我预想的要困难,因为我对C++一无所知。我遇到了这个我不太了解的片段。如果有人能告诉我标记的行会做什么,那真棒。翻译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); 
    } 
    } 

回答

5

insert成员函数返回一对,其bool组分如果插入物制成,假如果映射已经包含一个元件,其键曾在排序的等效值,其迭代器组件返回地址,以便返回true插入了一个新的元素或元素已经定位的位置。

这样的代码添加元素的map,如果元素是不是已经在那里它推数据到vector

+0

哦,好的,谢谢。我正在看的页面没有列出一对返回值..lame。我必须更加小心地处理我从中获取信息的网站。谢谢 –

+0

@Hunter - 返回一对不是“标准”行为。我想你正在使用VC++?依赖于向量插入的返回是不可移植的。所以你看到的页面可能没有错,它只是与你的编译器不匹配。 – Michael

+0

@Michael:不是一个向量插入,而是一个映射插入,并且该对返回在C++ 11标准中,这在C++ 03中无效吗? –

3

这里使用的insert成员函数,其中bool构件是true如果插入被做返回pair<iterator, bool>,。因此,if声明会看到insert调用是否实际向地图添加了一条记录。

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

+0

感谢您的评论,我没有看到我正在查看的页面上列出的返回类型。另外,谢谢你的链接 –