Hunter McMillen
Hunter McMillen

Reputation: 61510

translating C++ snippet

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

Upvotes: 4

Views: 101

Answers (2)

K-ballo
K-ballo

Reputation: 81349

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.

Upvotes: 5

Hugh
Hugh

Reputation: 8932

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.

Upvotes: 3

Related Questions