Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simpler form of std::unordered_map::insert?

Tags:

c++

c++11

stl

Is there an easier way to check whether an std::unordered_map::insert call succeeded than writing this mammoth block of code?

std::pair< T1, T2 > pair(val1, val2);
std::pair< std::unordered_map< T1, T2 >::const_iterator, bool> ret =
 _tileTypes.insert(pair);
if(!ret.second) {
    // insert did not succeed
}
like image 575
Mr. Smith Avatar asked Jan 01 '13 19:01

Mr. Smith


2 Answers

How about just:

if(!_tileTypes.insert(std::make_pair(val1, vla2)).second) {
    // insert did not succeed
}
like image 170
Ivaylo Strandjev Avatar answered Oct 14 '22 08:10

Ivaylo Strandjev


if (!_tileTypes.insert(pair).second)

?

Alternatively, typedefs can be useful to tidy this sort of thing up.

Also, if you're using C++11, then you can use the auto keyword to infer the type:

auto ret = _tileTypes.insert(pair);
like image 20
Oliver Charlesworth Avatar answered Oct 14 '22 07:10

Oliver Charlesworth