Home > Mobile >  How to use structured bindings to set array's values?
How to use structured bindings to set array's values?

Time:09-23

I'm new to C 17 and I ran into a problem when I tried to use structure binding to set values to a couple of array cells. But the regular syntax doesn't work here, it gets confused with the array's brackets.

Anyone knows how to solve it? Is it even possible?

Example:

std::pair<int, int> makePair() {
    return { 10, 20 };
}

int main() {
    int arr[20];

    // error here
    auto [arr[0], arr[1]] = makePair();
}

CodePudding user response:

Wrong tool for the job. Structured bindings always introduce new names, they don't accept arbitrary expressions for lvalues.

But you can do what you want even in C 11. There's std::tie, for this exact purpose:

std::tie(arr[0], arr[1]) = makePair();

Give it a bunch of lvalues for arguments, and it will produce a tuple of references to them. std::tuple interacts with std::pair (considered as two-tuple), and the member-wise assignment modifies the array elements you named.

  • Related