Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

translating C++ snippet

Tags:

c++

I am working on porting a framework from C++ to Java, and it is turning out to be harder than I expected, as I don't know a whole lot about C++. I came across this one snippet that I don't really understand. If someone could tell me what the lines marked do that would be awesome.

  /** 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);
    }
  }
like image 926
Hunter McMillen Avatar asked Feb 23 '23 20:02

Hunter McMillen


2 Answers

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.

So that code is adding an element to the map, and if the element wasn't already there it pushes the data into the vector.

like image 174
K-ballo Avatar answered Mar 07 '23 11:03

K-ballo


The insert member function used here returns a pair<iterator, bool>, where the bool member is true if an insertion was made. So, the if statement is seeing if the insert call actually added a record to the map.

You might find it useful to refer to the documentation of the standard library when working with C++ - here's the MSDN page on map::insert.

like image 43
Hugh Avatar answered Mar 07 '23 12:03

Hugh