Is it possible to assign the members of a pair without creating a temporary object?
#include <tuple>
using namespace std;
pair< bool, int > foo()
{
return make_pair( false, 3 );
}
int main()
{
int x;
bool y;
auto z = foo();
x = z.second;
y = z.first;
return 0;
}
In the above code, the object auto z
is needed to "hold" the pair before dissecting it, but its creation might be expensive in the actual code.
1) make_pair(): This template function allows to create a value pair without writing the types explicitly. Syntax: Pair_name = make_pair (value1,value2); CPP.
C++ Programming In C++ 17, there are introduced two new ways by which a programmer can assign values to a variable or declared them. In this update, elser then the classical way of assigning values to a variable the following two ways to initialise values.
The default constructor of std::pair would value-initialize both elements of the pair, that means for pair<int, int> res; , its first and second would be initialized to 0 . That's the only way you can check for a default-constructed std::pair , if they're guaranteed to be non-zero after the assignment.
Yes; std::tie
was invented for this:
#include <tuple>
#include <iostream>
std::pair<bool, int> foo()
{
return std::make_pair(false, 3);
}
int main()
{
int x;
bool y;
std::tie(y, x) = foo();
std::cout << x << ',' << y << '\n';
}
// Output: 3,0
Of course you are still going to have a temporary object somewhere (modulo constant optimisations), but this is the most direct you can write the code unless you initialise x
and y
directly from their eventual values rather than first creating a pair inside foo()
.
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