Vector<pair>: emplace without constructing pair-inner objects

51 Views Asked by At

Suppose we have two structs:

struct FIRST{
    int a=0;
    int b=0;
    FIRST(int a, int b): a(a), b(b){}
};
struct SECOND{
    int c=0;
    int d=0;
    SECOND(int c, int d): c(c), d(d){}
};

And we have a vector of pairs of them:

std::vector<std::pair<FIRST, SECOND>> abcd;

What I want is to emplace a pair without constructing both elements, so this is not what I want:

abcd.emplace_back(FIRST(1,2),SECOND(3,4));

But this is not going to work

abcd.emplace_back(1,2,3,4);

How? Is it even possible?

1

There are 1 best solutions below

0
HolyBlackCat On BEST ANSWER

Use std::piecewise_construct:

abcd.emplace_back(
    std::piecewise_construct,
    std::forward_as_tuple(1, 2),
    std::forward_as_tuple(3, 4)
);