如何将 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;
}

问题:

  1. 我可以以某种方式在 unordered_map 的键值对中分配值吗?
  2. 为什么不允许从取自 const unordered_map 的向量中分配整数? & 来自常量向量是否允许?

提前致谢!

解决方法

std::(unordered_)mapoperator[] 只是一个非 const 运算符,因为如果找不到请求的键,它将修改映射以插入新元素。但是在 fun() 内部,direct_paths 是(对)const 地图对象的(引用),因此无法对其调用 operator[]。这就是编译器所抱怨的,因为您不能在 const 对象上调用非 const 方法。

std::vectoroperator[] 没有这样的限制,因为它被重载用于 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;
}