如何将constunordered_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,2,3};
fun(a);
return 0;
}
问题:
- 我可以以某种方式在 unordered_map 的键值对中分配值吗?
- 为什么不允许从取自 const unordered_map<int, vector&> 的向量中分配整数?& 来自 const 向量允许吗?
提前致谢!
回答
该operator[]的std::(unordered_)map是非const唯一运营商,因为它会修改地图中插入一个新的元素,如果被请求的关键是找不到的。但是在fun(),内部direct_paths是(对)const地图对象的引用,因此operator[]不能对其调用。这就是编译器所抱怨的,因为您不能const在const对象上调用非方法。
所述operator[]的std::vector没有这样的限制,因为它是载于工作与两个const和非const矢量对象。
要修复您看到的错误,您需要改用地图的at()orfind()方法,它们都可以在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;
}
- @NathanPierson my way of getting along with this inconsistency is to accept that `unordered_map::operator[]` is not element access, rather it is element access and insertion. Its a good reminder of why one needs to be careful with operator overloading 😉
THE END
二维码