Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to treat std::pair as two separate variables?

Tags:

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.

like image 346
Mark Ransom Avatar asked Mar 19 '14 23:03

Mark Ransom


2 Answers

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.

like image 144
Timothy Shields Avatar answered Sep 23 '22 01:09

Timothy Shields


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));
like image 39
Chris Avatar answered Sep 21 '22 01:09

Chris