【问题标题】:How to use map as data type inside multiset in C++如何在 C++ 中的多重集中使用映射作为数据类型
【发布时间】:2021-05-17 08:04:00
【问题描述】:

我正在尝试为多重集使用地图数据类型结构。这是我下面的代码

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

【问题讨论】:

    标签: c++ stl c++-standard-library


    【解决方案1】:

    multiset 的两个参数 insert 成员都没有从参数构造值,即使它们构造了,1, 4 也无法初始化 map&lt;int, int&gt;

    如果你想要一个包含单个元素 1, 4 的地图,你需要指定它

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

    【讨论】:

    • 谢谢你的作品。但是如果我想打印multiset_map的元素那我该怎么办呢?
    • @superflash 你需要定义一种方式来打印map&lt;int, int&gt;
    猜你喜欢
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 2018-10-12
    相关资源
    最近更新 更多