Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assigning members of a pair to variables

Tags:

c++

c++11

c++14

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.

like image 584
Hector Avatar asked Aug 03 '15 17:08

Hector


People also ask

How do you assign values to a pair in C++?

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.

Can we assign value in class in C++?

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.

How do you know if a pair is empty?

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.


1 Answers

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

(live demo)

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().

like image 84
Lightness Races in Orbit Avatar answered Sep 28 '22 07:09

Lightness Races in Orbit