Can I use tie to put Elements of a pair in a vector?

986 Views Asked by At

So lets say that I have a function like: pair<int, int> func() and a vector<int> vec. I want to do this:

vec.resize(size(vec) + 2U);

tie(*next(rbegin(vec)), *rbegin(vec)) = func();

I just feel like this is a really complicated way to write what I'm doing. Is there a way to accomplish this without the resize call and all that?

2

There are 2 best solutions below

0
Max Langhof On

You might use structured bindings (C++17) and push_back instead:

auto [elem1, elem2] = func();

vec.push_back(elem1);
vec.push_back(elem2);

That's definitely way easier to read.

0
Vittorio Romeo On

Simple C++17 solution with structured bindings:

std::pair<int, int> func();

int main()
{
    std::vector<int> vec;
    vec.reserve(2);

    const auto [a, b] = func();
    vec.push_back(a);
    vec.push_back(b);
}  

live example on godbolt.org


C++17 pack expansion solution:

const auto vec = std::apply([](auto... xs)
{
    return std::vector{xs...};
}, func());

live example on godbolt.org


C++17 pack expansion solution (in an existing vector):

std::vector<int> vec;
std::apply([&vec](auto... xs)
{
    (vec.push_back(xs), ...);
}, func());