Convert a Vector to Set in C++

In this tutorial, we try to convert a vector of elements into a set of elements in C++.

Vectors in C++ are not new but are in fact containers similar to arrays that can expand or shrink in size. Even vectors store elements in a contiguous manner like an array in cpp. But the difference is that their size can change dynamically at run time as per requirements. A set is also a container, but a set only stores unique values. That means that a set has no redundant or repeating values.

Converting from vector to set would require us to remove duplicate values while transfer. The simplest way is to create an empty set, traverse through the vector and insert unique values into the set. Then we print the set values.

A C++ code for the same would look like the code given below:

#include <bits/stdc++.h>
using namespace std;


int main()
{
  vector<int> a({ 5,5,5,7,8,8,9,2,2 });

  unordered_set<int> s;
  for (const int &i: a) {
    s.insert(i);
  }

  for (const int &i: s) {
      cout << i << " ";
  }

  return 0;
}

The output for the above code would be:

2 9 8 5 7
...program finished with exit code 0

That’s it. I hope this article helps you to understand how to convert a vector to a set in C++ language.

Leave a Reply

Your email address will not be published.