Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying a tuple in a vector of tuples c++

I have a vector of tuples vector<tuple<int,int>> vector; and I want to modify one of the tuples it contains.

for (std::tuple<int, int> tup : std::vector)
{
    if (get<0>(tup) == k)
    {
        /* change get<1>(tup) to a new value
         * and have that change shown in the vector
         */
    }
}

I am unsure how to change the value of the tuple and have the change be reflected in the vector. I have tried using

get<1>(tup) = v;

but that doesn't change the value of the tuple that is in the vector. How can I do this? Thanks.

like image 878
jjacobson Avatar asked Mar 05 '15 09:03

jjacobson


People also ask

Can you have a vector of tuples?

A tuple is an object that can hold a number of elements and a vector containing multiple number of such tuple is called a vector of tuple. The elements can be of different data types. The elements of tuples are initialized as arguments in order in which they will be accessed.

Can you have a vector of tuples in C++?

This article focuses on how to create a 2D vector of tuples in C++. A 2D vector of tuples or vector of vectors of tuples is a vector in which each element is a vector of tuples itself. Although a tuple may contain any number of elements for simplicity, a tuple of three elements is considered.

Can tuple be modified?

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.


2 Answers

Capture the tuple by reference:

for (tuple<int, int> &tup : vector){
//                   ^here
    if (get<0>(tup) == k){
        get<1>(tup) = v;
    }
}
like image 73
TartanLlama Avatar answered Sep 28 '22 16:09

TartanLlama


You just need to use a reference instead of a value in your for-loop:

for (tuple<int, int>& tup : vector){
like image 43
John Zwinck Avatar answered Sep 26 '22 16:09

John Zwinck