How to Convert Vector to Multiset in C++?
Last Updated :
09 Feb, 2024
In C++, vector is a dynamic array that allows us to store multiple elements sequentially and multiset is a container that allows us to store multiple elements having duplicate values in some sorted order. In this article, we will learn how to convert a vector to multiset in C++.
For Example
Input:
myVector = {2, 4, 9, 1, 3, 5, 4, 3, 2}
Output:
myMultiset = {1, 2, 2, 3, 3, 4, 4, 5, 9}
Assign Vector to Multiset in C++
To convert vector to multiset in C++, we can simply use a range constructor of multiset
which takes iterators of the vector as arguments.
Syntax of Multiset Ranged Constructor
multiset<type> myMultiset(first, last);
The first iterator points to the start of the range and the last iterator points to the end of the range.
C++ Program to Convert Vector to Multiset in C++
C++
#include <iostream>
#include <set>
#include <vector>
using namespace std;
int main()
{
vector< int > nums = {2, 4, 9, 1, 3, 5, 4, 3, 2};
multiset< int > myMultiset(nums.begin(), nums.end());
cout << "Elements of multiset are: " ;
for ( const auto & i : myMultiset) {
cout << i << " " ;
}
return 0;
}
|
Output
Elements of multiset are: 1 2 2 3 3 4 4 5 9
Time Complexity: O(N logN), where N is the number of elements
Space Complexity: O(N)
Share your thoughts in the comments
Please Login to comment...