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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With