Related Articles
How to store Data Triplet in a Vector in C++?
• Difficulty Level : Easy
• 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
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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``using` `namespace` `std;`` ` `struct` `Test``{``   ``int` `x, y, z;``};`` ` `int` `main()``{``    ``// Creating a vector of Test``    ``vector 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

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``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

Output:

```2, 31, 102
5, 23, 114
9, 10, 158
```

This article is contributed by Jatin Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up