Ask Your Question
4

How can two vectors in c++ be combined into a tuple using the zip function?

asked 2022-07-08 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-04-14 19:00:00 +0000

pufferfish gravatar image

To combine two vectors into a tuple using the zip function in C++, you can use the std::tuple class and the std::vector class from the Standard Template Library (STL).

Here's an example code snippet that combines two vectors into a tuple using the std::transform, std::begin, and std::end functions:

#include <iostream>
#include <vector>
#include <tuple>
#include <algorithm>

int main() {
    std::vector<int> v1 {1, 2, 3, 4};
    std::vector<double> v2 {1.1, 2.2, 3.3, 4.4};

    std::vector<std::tuple<int, double>> tuple_vec;
    tuple_vec.reserve(std::min(v1.size(), v2.size()));

    std::transform(std::begin(v1), std::end(v1), std::begin(v2),
        std::back_inserter(tuple_vec), [](const auto& x, const auto& y) {
            return std::make_tuple(x, y);
        });

    for (const auto& t : tuple_vec) {
        std::cout << "(" << std::get<0>(t) << ", " << std::get<1>(t) << ")\n";
    }

    return 0;
}

In this example, we first define two vectors v1 and v2 of integers and doubles, respectively. We then define a new vector tuple_vec of tuples that will hold the combined data from v1 and v2. We reserve the size of tuple_vec to be the smaller of the sizes of v1 and v2.

We then use the std::transform algorithm to combine the two vectors into tuples using a lambda function. The lambda function takes two arguments, x from v1 and y from v2, and returns a new tuple that combines x and y.

Finally, we use a range-based for loop to print out the tuples in tuple_vec. Each tuple is accessed using the std::get function and the appropriate index for the tuple element.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-07-08 11:00:00 +0000

Seen: 14 times

Last updated: Apr 14 '21