One can get an element from std::tuple
by index using std::get
. Analogically, how to set tuple's element by index?
1. get(): get() is used to access the tuple values and modify them, it accepts the index and tuple name as arguments to access a particular tuple element. 2. make_tuple(): make_tuple() is used to assign tuple with values.
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called. But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.
The way to get the nth item in a tuple is to use std::get: std::get<n>(my_tuple) .
A tuple is an object capable to hold a collection of elements where each element can be of a different type. The class template needs the header <tuple> . std::tuple is a generalization of std::pair. You can convert between tuples with two elements and pairs.
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));
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With