Open In App

How to Create a Set of Vectors in C++?

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// C++ program to create set for vectors
  
#include <iostream>
#include <set>
#include <vector>
using namespace std;
  
int main()
{
  
    // Creating set of vectors
    // that will store each vector
    set<vector<int> > st;
  
    // Initializing vectors
    vector<int> vec1{ 1, 2, 3 };
    vector<int> vec2{ 4, 5, 6 };
    vector<int> vec3{ 1, 2, 3 };
  
    // Inserting the above vectors into the set
    st.insert(vec1);
    st.insert(vec2);
    st.insert(vec3);
  
    // Iterating and printing vectors from the set
    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)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads