首页 > 解决方案 > 如何在 C++ 中为 multimap 实现以下函数 getValue(m)

问题描述

#include<bits/stdc++.h>
using namespace std;
void getValue(multimap<int,string> &m){
    for(auto &mValue : m){
        cout<<mValue.first<<" "<<mValue.second<<endl;
    }
}
int main(){
    int n;
    cin>>n;
    multimap<int,string> m;
    
    for(int i=0;i<n;i++){
        int num;
        string str;
        cin>>num;
        getline(cin,str);
        m.insert(make_pair(num,str));
    }
    

    getValue(m);
    return 0;
}

错误: 从类型“std::multimap >”getValue(m) 的表达式中对类型“std::map >&”的引用无效初始化;

标签: c++c++11multimap

解决方案


std::map<int, std::string>是与 不同的类型std::multimap<int, std::string>,尽管它们有相似之处。

最简单的方法是编写类似的函数:

void getValue(const std::multimap<int, std::string> &m){
    for(auto &mValue : m){
        std::cout<<mValue.first<<" "<<mValue.second<<std::endl;
    }
}

但是std,内外有许多类似地图的容器,因此您可能希望更改getValue为模板

template <typename Map>
void getValue(const Map &m){
    for(auto &mValue : m){
        std::cout<<mValue.first<<" "<<mValue.second<<std::endl;
    }
}

您可能希望将其限制为仅接受类似地图的类型,例如(使用 C++17 的库添加std::void_t

template <typename Map>
std::void_t<typename Map::key_type, typename Map::mapped_type> getValue(const Map &m){
    for(auto &mValue : m){
        std::cout<<mValue.first<<" "<<mValue.second<<std::endl;
    }
}

推荐阅读