Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

In C++03, you must write like this:

std::pair< map<int, int>::iterator, bool > res = mymap.insert(std::make_pair(42, 1));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top