convert vector to set c++
To convert a vector to a set in C++, you can follow these steps:
Include the necessary header files:
cpp #include <vector> #include <set>
Create a vector and populate it with elements:
cpp std::vector<int> myVector = {1, 2, 3, 4, 5};
Create a set and initialize it with the elements from the vector:
cpp std::set<int> mySet(myVector.begin(), myVector.end());
In this step, we use the constructor of the std::set
class that takes two iterators. The first iterator points to the beginning of the range (in this case, the beginning of the vector), and the second iterator points to the end of the range (in this case, the end of the vector).
- Now, the
mySet
set contains the same elements as themyVector
vector, but in a sorted and unique order. If the vector contains duplicate elements, the set will only have one copy of each distinct element.
Here's the complete code example:
#include <vector>
#include <set>
int main() {
std::vector<int> myVector = {1, 2, 3, 4, 5};
std::set<int> mySet(myVector.begin(), myVector.end());
// Print the elements in the set
for (const auto& element : mySet) {
std::cout << element << " ";
}
std::cout << std::endl;
return 0;
}
This code will output: 1 2 3 4 5
, which are the elements in the set after converting the vector to a set.