如何解决如何将 const unordered_map 中的值分配给另一个 const 变量 - C++
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
void fun(const unordered_map<int,vector<int>>& direct_paths) {
const int var = direct_paths[1][0];
cout << var;
}
int main()
{
unordered_map<int,vector<int>> a;
a[1] = vector<int> {1,2,3};
fun(a);
return 0;
}
error: passing ‘const std::unordered_map<int,std::vector<int> >’ as ‘this’ argument discards qualifiers [-fpermissive]
const int var = direct_paths[1][0];
^
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
void fun(const vector<int>& direct_paths) {
const int var = direct_paths[1];
cout << var;
}
int main()
{
vector<int> a;
a = vector<int> {1,3};
fun(a);
return 0;
}
问题:
提前致谢!
解决方法
std::(unordered_)map
的 operator[]
只是一个非 const
运算符,因为如果找不到请求的键,它将修改映射以插入新元素。但是在 fun()
内部,direct_paths
是(对)const
地图对象的(引用),因此无法对其调用 operator[]
。这就是编译器所抱怨的,因为您不能在 const
对象上调用非 const
方法。
std::vector
的 operator[]
没有这样的限制,因为它被重载用于 const
和非 const
向量对象。
要修复您看到的错误,您需要改用地图的 at()
或 find()
方法,这两个方法都可以在 const
地图对象上调用,例如:>
void fun(const unordered_map<int,vector<int>>& direct_paths) {
const int var = direct_paths.at(1)[0]; // will throw an exception if key '1' is not found...
cout << var;
}
void fun(const unordered_map<int,vector<int>>& direct_paths) {
auto iter = direct_paths.find(1); // will return the end() iterator if key '1' is not found...
if (iter == direct_paths.end()) return; // or throw...
const int var = iter->second[0];
cout << var;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。