How to store Data Triplet in a Vector in C++?
Last Updated :
06 Jul, 2017
Given a vector, how can we store 3 elements in one cell of vector.
Examples:
Input : 2 5 10
3 6 15
Output : (2, 5, 10) // In first cell of vector
(3, 6, 15) // In second cell of vector
One solution is to create a user defined class or structure. We create a structure with three members, then create a vector of this structure.
#include<bits/stdc++.h>
using namespace std;
struct Test
{
int x, y, z;
};
int main()
{
vector<Test> myvec;
myvec.push_back({2, 31, 102});
myvec.push_back({5, 23, 114});
myvec.push_back({9, 10, 158});
int s = myvec.size();
for ( int i=0;i<s;i++)
{
cout << myvec[i].x << ", " << myvec[i].y
<< ", " << myvec[i].z << endl;
}
return 0;
}
|
Output :
2, 31, 102
5, 23, 114
9, 10, 158
Another solution is to use pair class in C++ STL. We make a pair with first element as normal element and second element as another pair, therefore storing 3 elements simultaneously.
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector< pair< int , pair< int , int > > > myvec;
myvec.push_back(make_pair(2, make_pair(31, 102)));
myvec.push_back(make_pair(5, make_pair(23, 114)));
myvec.push_back(make_pair(9, make_pair(10, 158)));
int s = myvec.size();
for ( int i=0; i<s; i++)
{
cout << myvec[i].first << ", " << myvec[i].second.first
<< ", " << myvec[i].second.second << endl;
}
return 0;
}
|
Output:
2, 31, 102
5, 23, 114
9, 10, 158
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...