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

edit retag close merge delete

Sort by ยป oldest newest most voted

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.

more