Reputation: 308111
There are a few functions in the standard library, such as std::map::insert
, which return a std::pair
. At times it would be convenient to have that populate two different variables corresponding to the halves of the pair. Is there an easy way to do that?
std::map<int,int>::iterator it;
bool b;
magic(it, b) = mymap.insert(std::make_pair(42, 1));
I'm looking for the magic
here.
Upvotes: 24
Views: 6819
Reputation: 231
In C++17, you can use structured bindings. So you don't have to declare the variables first:
auto [it, b] = mymap.insert(std::make_pair(42, 1));
Upvotes: 17
Reputation: 10254
In C++03, you must write like this:
std::pair< map<int, int>::iterator, bool > res = mymap.insert(std::make_pair(42, 1));
Upvotes: 0
Reputation: 79441
std::tie
from the <tuple>
header is what you want.
std::tie(it, b) = mymap.insert(std::make_pair(42, 1));
"magic
" :)
Note: This is a C++11 feature.
Upvotes: 33