繁体   English   中英

如何在 C++ 的多集中使用 map 作为数据类型

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

我正在尝试对多集使用 map 数据类型结构。 这是我下面的代码

#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;
}

我知道有一种多映射类型的数据结构,但我想在多集中实现它。 当我尝试插入元素时,它显示编译错误。

这是什么原因? 我尝试在网上搜索,但似乎没有人做过这种事情

错误:

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);

multiset的两个参数insert成员都没有从参数构造值,即使它们这样做了, 1, 4也无法初始化map<int, int>

如果您想要一个具有单个元素1, 4的 map,您需要指定

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM