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++
// Program to demonstrate converting a vector to a multiset #include <iostream> #include <set> #include <vector> using namespace std;
int main()
{ // Creating a vector
vector< int > nums = {2, 4, 9, 1, 3, 5, 4, 3, 2};
// Converting vector to multiset
multiset< int > myMultiset(nums.begin(), nums.end());
// Printing the elements of the multiset
cout << "Elements of multiset are: " ;
for ( const auto & i : myMultiset) {
cout << i << " " ;
}
return 0;
} |
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)