Open In App

How to store Data Triplet in a Vector in C++?

Last Updated : 06 Jul, 2017
Improve
Improve
Like Article
Like
Save
Share
Report

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.




// C++ program to store data triplet in a vector
// using user defined structure.
#include<bits/stdc++.h>
using namespace std;
  
struct Test
{
   int x, y, z;
};
  
int main()
{
    // Creating a vector of Test
    vector<Test> myvec;
  
    // Inserting elements into vector. First
    // value is assigned to x, second to y
    // and third to z.
    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++)
    {
        // Accessing structure members using their
        // names.
        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.




// C++ program to store data triplet in a vector
// using pair class
#include<bits/stdc++.h>
using namespace std;
  
int main()
{
    // We make a pair with first element as normal
    // element and second element as another pair.
    // therefore 3 elements simultaneously.
    vector< pair<int, pair<int, int> > > myvec;
  
    // For inserting element in pair use
    // make_pair().
    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++)
    {
        // The elements can be directly accessed
        // according to first or second element
        // of the pair.
        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
Previous
Next
Share your thoughts in the comments

Similar Reads