129

One can get an element from std::tuple by index using std::get. Analogically, how to set tuple's element by index?

2 Answers 2

186

std::get returns a reference to the value. So you set the value like this:

std::get<0>(myTuple) = newValue;

This of course assumes that myTuple is non-const. You can even move items out of a tuple via std::move, by invoking it on the tuple:

auto movedTo = std::get<0>(std::move(myTuple));
Sign up to request clarification or add additional context in comments.

Comments

29

The non-const version of get returns a reference. You can assign to the reference. For example, suppose t is tuple, then: get<0>(t) = 3;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.