How to Create a Set of Vectors in C++?
Last Updated :
22 Feb, 2024
In C++, a set is a type of associative container in which duplicate elements are not allowed and a vector is a dynamic array in which duplicate elements are allowed. In this article, we will learn how to create a set of vectors in C++.
For Example,
Input:
vector<int> vec1={1, 2, 3};
vector<int> vec2={4, 5, 6};
vector<int> vec3={1, 2, 3};
Output:
Set Elements are:
{1 2 3}
{4 5 6}
Declaring a Set of Vectors in C++
To create a set of vectors, first declare a std::set
with std::vector<dataType>
as its template parameter and then add the vectors to the set using set::insert()
method.
Syntax to Declare Set of Vectors in C++
set<vector<datatype>> setOfVector;
In the above set, each element will be a vector of type ‘datatype’
C++ Program to Create a Set of Vectors
C++
#include <iostream>
#include <set>
#include <vector>
using namespace std;
int main()
{
set<vector< int > > st;
vector< int > vec1{ 1, 2, 3 };
vector< int > vec2{ 4, 5, 6 };
vector< int > vec3{ 1, 2, 3 };
st.insert(vec1);
st.insert(vec2);
st.insert(vec3);
cout << "Set Elements are: " << endl;
for ( auto & it : st) {
for ( int elem : it) {
cout << elem << " " ;
}
cout << endl;
}
return 0;
}
|
Output
Set Elements are:
1 2 3
4 5 6
Time Complexity: O(N * M log N), here N
is the number of vectors in the set and M
is the average size of the vectors.
Auxiliary Space: O(N * M)
Share your thoughts in the comments
Please Login to comment...