How to set std::tuple element by index?

C++TemplatesIndexingTuples

C++ Problem Overview


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

C++ Solutions


Solution 1 - C++

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));

Solution 2 - C++

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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBehrouz.MView Question on Stackoverflow
Solution 1 - C++Nicol BolasView Answer on Stackoverflow
Solution 2 - C++amit kumarView Answer on Stackoverflow