How to Create a Vector of Tuples in C++?
In C++, a tuple is an object that allows the users to store elements of various data types together while a vector is used to store elements of the same data types. In this article, we will learn how we can create a vector of tuples in C++.
Example:
Input:
Tuple1 ={10,A,5.3} Tuple2= {20,B,6.5}
Output:
Vector Elements:
Tuple 1: 10, A, 5.3
Tuple 2: 20, B, 6.5
Vector of Tuples in C++
To create a vector of tuples, we will have to first declare a vector of type tuple. It means that each element of the vector will be a tuple. Moreover, we also have to specify the type of tuple.
Syntax
vector<tuple<type1, type2, ...>> myVector.
We can simply use the std::make_tuple() method to insert the data into the vector.
For traversing, we can use the tuple::get() method to iterate over the elements of the tuple present in the vector.
C++ Program to Create a Vector of Tuples
// C++ program to create a vector of tuples
#include <iostream>
#include <vector>
#include <tuple>
using namespace std;
int main() {
// Intialize a vector of tuples
vector<tuple<int, char, float>> vecOfTuples;
// Add tuples to the vector
vecOfTuples.push_back(make_tuple(10, 'A', 3.14));
vecOfTuples.push_back(make_tuple(20, 'B', 6.28));
vecOfTuples.push_back(make_tuple(30, 'C', 9.42));
vecOfTuples.push_back(make_tuple(40, 'D', 10.8));
// Iterate over the vector and print each tuple
int i=1;
cout<<"Vector Elements:"<<endl;
for (const auto& tuple : vecOfTuples) {
// Access tuple elements using get<index>(tuple)
cout << "Tuple "<<i<<": " << get<0>(tuple) << ", " << get<1>(tuple) << ", " << get<2>(tuple) << endl;
i++;
}
return 0;
}
// C++ program to create a vector of tuples
using namespace std;
int main() {
// Intialize a vector of tuples
vector<tuple<int, char, float>> vecOfTuples;
// Add tuples to the vector
vecOfTuples.push_back(make_tuple(10, 'A', 3.14));
vecOfTuples.push_back(make_tuple(20, 'B', 6.28));
vecOfTuples.push_back(make_tuple(30, 'C', 9.42));
vecOfTuples.push_back(make_tuple(40, 'D', 10.8));
// Iterate over the vector and print each tuple
int i=1;
cout<<"Vector Elements:"<<endl;
for (const auto& tuple : vecOfTuples) {
// Access tuple elements using get<index>(tuple)
cout << "Tuple "<<i<<": " << get<0>(tuple) << ", " << get<1>(tuple) << ", " << get<2>(tuple) << endl;
i++;
}
return 0;
}
Output
Vector Elements: Tuple 1: 10, A, 3.14 Tuple 2: 20, B, 6.28 Tuple 3: 30, C, 9.42 Tuple 4: 40, D, 10.8
Time Complexity: O(N) where N is the number of tuples inside the vector
Auxiliary Space: O(N)