3

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?

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288

2 Answers2

4

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());
Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
1

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.

Max Langhof
  • 23,383
  • 5
  • 39
  • 72