2D Vector of Tuples in C++ with Examples
What is Vector?
In C++, a vector is similar to dynamic arrays with the ability to resize itself automatically. Vector elements are stored in contiguous memory locations so that they can be accessed and traversed using iterators.
Functions associated with a vector:
- begin(): Returns an iterator pointing to the first element in the vector.
- end(): Returns an iterator pointing to the theoretical element that follows the last element in the vector.
- rbegin(): Returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to the first element.
- size(): Returns the number of elements in the vector.
- empty(): Returns whether the vector is empty.
- push_back(): It pushes the elements into a vector from the back.
- pop_back(): It is used to pop or remove elements from a vector from the back.
- insert(): It inserts new elements before the element at the specified position.
What is a 2D vector?
In C++, a 2D vector is a vector of vectors which means that each element of a 2D vector is a vector itself. It is the same as a matrix implemented with the help of vectors.
Functions associated with a 2D vector:
- size(): Returns the number of elements in the 2D vector.
- empty(): Returns whether the 2D vector is empty.
- push_back(): It pushes a vector into a 2D vector from the back.
- pop_back(): It is used to pop or remove elements from a 2D vector from the back.
What is a Tuple?
A tuple in C++ is an object which is used to group elements together. In a tuple, elements can be of the same data type or different data types. The elements of tuples are initialized as in the order in which they will be accessed.
Functions associated with a tuple:
1. make_tuple(): make_tuple() is used to assign tuple with values. The values passed should be in order with the values declared in the tuple.
2. get(): get() is used to access the tuple values and modify them, it accepts the index and tuple name as arguments to access a particular tuple element.
How to access a Tuple?
To access elements of a tuple use the get<>() function.
auto fistElement = get<0>(myTuple);
auto secondElement = get<1>(myTuple);
auto thirdElement = get<2>(myTuple);
This article focuses on how to create a 2D vector of tuples in C++.
2D Vector of Tuples
A 2D vector of tuples or vector of vectors of tuples is a vector in which each element is a vector of tuples itself. Although a tuple may contain any number of elements for simplicity, a tuple of three elements is considered.
vector<vector<tuple<dataType1, dataType2, dataType3>> myContainer
dataType1, dataType2, dataType3 can be similar or dissimilar data types.
Example 1: Below is the C++ program to implement 2D vector of tuples.
Example 2: Below is the C++ program to implement 2D vector of tuples.
Time complexity: O(n^2). // n is the total number of elements in the 2D vector.
Space complexity: O(n).
Please Login to comment...