c++ - 如何在 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 >&”的引用无效初始化;
解决方案
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;
}
}
推荐阅读
- c++ - C++ 编译器可以优化这个吗
- javascript - 导航栏在不同浏览器上的显示不一致
- javascript - 请求 Ajax 未能获得 http 状态 403
- javascript - 如果它们包含一个或多个特殊字符,则使浏览器以备用字体显示整个 DOM 元素
- python - pip 在我尝试更改环境变量的 vs 代码中不起作用.. 我被这个困住了
- python - discord.py 在我的不和谐机器人中有错误如何解决?
- android - 最近我将最低 sdk 版本更改为 24 并收到 1 条关于可绘制如何解决此问题的 lint 警告?
- apache-spark - 当使用正则表达式在多列上运行时
- c# - 使用 C# 进行 XML 验证
- c++ - 为什么它不让我执行这个?