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.
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.
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.
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.
Capture the tuple
by reference:
for (tuple<int, int> &tup : vector){
// ^here
if (get<0>(tup) == k){
get<1>(tup) = v;
}
}
You just need to use a reference instead of a value in your for-loop:
for (tuple<int, int>& tup : vector){
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