Does structured binding work with std::vector?

前端 未结 3 867
隐瞒了意图╮
隐瞒了意图╮ 2020-12-15 03:40

Is it possible to use structured binding with vectors?

E.g.

std::vector vec{1, 2, 3};
auto [a, b, c] = vec;

Above code u

3条回答
  •  隐瞒了意图╮
    2020-12-15 04:14

    Not ideal since it's more verbose but you can also do:

    auto [a, b, c] = array({vec[0], vec[1], vec[2]});

    I do not agree with the notion that not knowing the number of elements of a container should prevent structured binding to it's elements. My reasoning is that since the following does not throw a compile time error:

    auto a = vec[0];
    auto b = vec[1];
    auto c = vec[2];
    

    (even though vec[2] might be out of range at run-time), so should be the case for the above structured binding. Meaning, why not leave it to the user to make sure vector has the correct length at runtime, and throw an out of range exception if that is not the case? That is essentially how we use vectors everywhere else in the language.

提交回复
热议问题