C ++ Translation - Fragment

I am working on porting the framework from C ++ to Java, and it turns out to be more complicated than I expected, since I do not know much about C ++. I stumbled upon this piece that I really don't understand. If anyone could tell me what the lines indicate, 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); } } 
+4
source share
2 answers

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

So, for the code to add an element to map , and if the element has not been there yet, it pushes data in vector .

+5
source

The insert member function used here returns a pair<iterator, bool> , where the bool element is true if an insert was made. So, the if sees that the insert call actually added an entry to the map.

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

+3
source

All Articles