How to convert a Vector to Set in C++
Last Updated :
01 Jun, 2022
This article shows how to convert a vector to a set in C++.
Example:
Input: vector = {1, 2, 3, 1, 1}
Output: set = {1, 2, 3}
Input: vector = {1, 2, 3, 3, 5}
Output: set = {1, 2, 3, 5}
Below are the various ways to do the required conversion:
- Method 1: Naive Solution
- Get the vector to be converted.
- Create an empty set, to store the result.
- Iterate through the vector one by one, and insert each element into the set.
- Print the resultant set.
C++
#include <iostream>
#include <set>
#include <vector>
using namespace std;
set< int > convertToSet(vector< int > v)
{
set< int > s;
for ( int x : v) {
s.insert(x);
}
return s;
}
void printSet(set< int > s)
{
cout << "Set: " ;
for ( int x : s) {
cout << x << " " ;
}
cout << endl;
}
void printVector(vector< int > vec)
{
cout << "Vector: " ;
for ( int x : vec) {
cout << x << " " ;
}
cout << endl;
}
int main()
{
vector< int > vec = { 1, 2, 3, 1, 1 };
printVector(vec);
set< int > s = convertToSet(vec);
printSet(s);
return 0;
}
|
Output
Vector: 1 2 3 1 1
Set: 1 2 3
- Method 2: Using Range Converter
- Get the vector.
- Define a set that copies all elements of the vector using 2 pointers begin and end.
- Print the set.
C++
#include <iostream>
#include <set>
#include <vector>
using namespace std;
set< int > convertToSet(vector< int > v)
{
set< int > s(v.begin(), v.end());
return s;
}
void printSet(set< int > s)
{
cout << "Set: " ;
for ( int x : s) {
cout << x << " " ;
}
cout << endl;
}
void printVector(vector< int > vec)
{
cout << "Vector: " ;
for ( int x : vec) {
cout << x << " " ;
}
cout << endl;
}
int main()
{
vector< int > vec = { 1, 2, 3, 1, 1 };
printVector(vec);
set< int > s = convertToSet(vec);
printSet(s);
return 0;
}
|
Output
Vector: 1 2 3 1 1
Set: 1 2 3
- Method 3: Using Copy():
- Get the vector.
- Define a set that copies all elements of the vector using the standard algorithm std::copy() method defined in the <algorithm> header.
- Print the set.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <set>
#include <vector>
using namespace std;
set< int > convertToSet(vector< int > v)
{
set< int > s;
copy(
v.begin(),
v.end(),
inserter(s, s.end()));
return s;
}
void printSet(set< int > s)
{
cout << "Set: " ;
for ( int x : s) {
cout << x << " " ;
}
cout << endl;
}
void printVector(vector< int > vec)
{
cout << "Vector: " ;
for ( int x : vec) {
cout << x << " " ;
}
cout << endl;
}
int main()
{
vector< int > vec = { 1, 2, 3, 1, 1 };
printVector(vec);
set< int > s = convertToSet(vec);
printSet(s);
return 0;
}
|
Output
Vector: 1 2 3 1 1
Set: 1 2 3
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...