How to set std::tuple element by index?

Behrouz.M picture Behrouz.M · Sep 17, 2011 · Viewed 46.6k times · Source

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

Answer

Nicol Bolas picture Nicol Bolas · Sep 17, 2011

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