Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set std::tuple element by index?

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

like image 368
Behrouz.M Avatar asked Sep 17 '11 08:09

Behrouz.M


People also ask

How to assign value to tuple in c++?

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.

How do you change the elements of a tuple?

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.

How to get the nth element of a tuple?

The way to get the nth item in a tuple is to use std::get: std::get<n>(my_tuple) .

Is std :: pair a 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.


2 Answers

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)); 
like image 106
Nicol Bolas Avatar answered Oct 08 '22 10:10

Nicol Bolas


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;

like image 34
amit kumar Avatar answered Oct 08 '22 10:10

amit kumar