C++ Tuple::operator=() Function



The C++ std::tuple::operator=() function is used to assign the values of one tuple to another of the same type. It allows for efficient copying of tuple contents, ensuring each element is assigned to its corresponding element in the target tuple.

By using this function we can easily manage and manipulate the tuples.

Syntax

Following is the syntax for std::tuple::operator=() function.

tuple& operator= (const tuple& tpl);tuple& operator= (tuple&& tpl) noexcept;

Parameters

  • tpl − It indicates the another tuple object with same nummer

Return Value

This function does not return anything.

Example

Let's look at the following example, where we are going to assign the contents of one tuple to another.

#include <iostream>
#include <tuple>
int main() {
    std::tuple<std::string, double> x("Welcome", 0.01);
    std::tuple<std::string, double> y;
    y = x; 
    std::cout << std::get<0>(y) << " " << std::get<1>(y) << " " <<std::endl;
    return 0;
}

Output

Let us compile and run the above program, this will produce the following result −

Welcome 0.01 

Example

Consider the another scenario, where we are going to assign the content of one tuple to another of different data type.

#include <iostream>
#include <tuple>
int main() {
    std::tuple<int, std::string> x(1, "TutorialsPoint");
    std::tuple<double, const char*> y;
    std::get<0>(y) = static_cast<double>(std::get<0>(x));
    std::get<1>(y) = std::get<1>(x).c_str(); 
    std::cout << std::get<0>(y) << " " << std::get<1>(y) << std::endl;
    return 0;
}

Output

If we run the above code it will generate the following output −

1 TutorialsPoint

Example

In the following example, we are going to assign tuple to itself using the operator=() function and observing the output.

#include <iostream>
#include <tuple>
int main()
{
    std::tuple<std::string, double> x("TP", 1.12);
    x = x;
    std::cout << std::get<0>(x) << " " << std::get<1>(x) << " " << std::endl;
    return 0;
}

Output

Following is the output of the above code −

TP 1.12

Example

Following is the example, where we are going to use the operator=() funtion along with a tie.

#include <iostream>
#include <tuple>
int main()
{
    int x, y, z;
    std::tuple<int, double, char> a(12, 0.01, 'c');
    std::tie(x, y, z) = a;
    std::cout << "x: " << x << ", y: " << y << ", z: " << z << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

x: 12, y: 0, z: 99
Advertisements