superflash
superflash

Reputation: 40

How to use map as data type inside multiset in C++

I am trying to use a map data type structure for multiset. This is my code below

#include <iostream>
#include <set>
#include <iterator>
#include <map>
#include <functional>

using namespace std;

int main()
{
   map<string, int> student_marks_map;
   student_marks_map["Student1"] = 100;
   student_marks_map["Student2"] = 20;
   student_marks_map["Student3"] = 230;

   multiset<int, greater<int>> multiset1 = {1,2,3,2,10};
   multiset<int, greater<int>>::iterator itr;
   //multiset1.insert(1);
   for(itr = multiset1.begin(); itr != multiset1.end(); itr++)
   {
       cout<<*itr<<endl;
   }

   multiset<map<int, int>> multiset_map;
   multiset_map.insert(1,4);

   /*for(const auto& iter: multiset1)
   {
      cout<< iter <<endl;
   }*/
   return 0;
}

I know there is a multimap type of data structure but I want to implement it in multiset. It is showing compiling errors when I try to insert an element.

What is the reason for this? I tried searching on the net but there does not seem to be anyone who has done this kind of thing

The Errors:

In file included from /usr/include/c++/7/set:60:0,
             from main.cpp:2:
/usr/include/c++/7/bits/stl_tree.h: In instantiation of ‘void std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_equal(_II, _II) [with _InputIterator = int; _Key = std::map<int, int>; _Val = std::map<int, int>; _KeyOfValue = std::_Identity<std::map<int, int> >; _Compare = std::less<std::map<int, int> >; _Alloc = std::allocator<std::map<int, int> >]’: /usr/include/c++/7/bits/stl_multiset.h:542:4:   required from ‘void std::multiset<_Key, _Compare, _Alloc>::insert(_InputIterator, _InputIterator) [with _InputIterator = int; _Key = std::map<int, int>; _Compare = std::less<std::map<int, int> >; _Alloc = std::allocator<std::map<int, int> >]’ <span class="error_line" onclick="ide.gotoLine('main.cpp',26)">main.cpp:26:28</span>:   required from here /usr/include/c++/7/bits/stl_tree.h:2464:28: error: invalid type argument of unary ‘*’ (have ‘int’) _M_insert_equal_(end(), *__first, __an);

Upvotes: 0

Views: 333

Answers (1)

Caleth
Caleth

Reputation: 62636

None of the two parameter insert members of multiset construct a value from the parameters, and even if they did, 1, 4 can't initialise a map<int, int>.

If you want a map with the single element 1, 4, you need to specify that

multiset_map.insert(map<int, int>{{1,4}});

Upvotes: 1

Related Questions