【问题标题】:map operator [] operands映射运算符 [] 操作数
【发布时间】:2010-05-05 10:05:16
【问题描述】:

大家好,我在成员函数中有以下内容

int tt = 6; 
vector<set<int>>& temp = m_egressCandidatesByDestAndOtMode[tt]; 
set<int>& egressCandidateStops = temp.at(dest);

以及下面的成员变量声明

map<int, vector<set<int>>> m_egressCandidatesByDestAndOtMode;

但是编译时出现错误(Intel Compiler 11.0)

1>C:\projects\svn\bdk\Source\ZenithAssignment\src\Iteration\PtBranchAndBoundIterationOriginRunner.cpp(85): error: no operator "[]" matches these operands
1>            operand types are: const std::map<int, std::vector<std::set<int, std::less<int>, std::allocator<int>>, std::allocator<std::set<int, std::less<int>, std::allocator<int>>>>, std::less<int>, std::allocator<std::pair<const int, std::vector<std::set<int, std::less<int>, std::allocator<int>>, std::allocator<std::set<int, std::less<int>, std::allocator<int>>>>>>> [ const int ]
1>          vector<set<int>>& temp = m_egressCandidatesByDestAndOtMode[tt]; 
1>                                                                    ^

我知道这一定很愚蠢,但我看不出我做错了什么。

更新我从一个 const 成员函数调用它,这就是为什么成员变量的类型是 const 所以我认为类似下面的东西应该修复它:

int dest = 0, tt = 6; 
const set<int>& egressCandidateStops = m_egressCandidatesByDestAndOtMode[tt].at(dest); 

但是没有骰子...仍然是同样的错误。

【问题讨论】:

  • Potatoswatter 的回答是正确的。为避免您的问题,您需要使用 find。

标签: c++ map operands


【解决方案1】:

操作数类型是:const std::map

map::operator[] 不适用于const map

我几天前answered这个。

map::operator[] 有点奇怪。它 这样做:

  1. 寻找钥匙。
  2. 如果找到,请退回。
  3. 如果没有,插入它并默认构造它的关联 价值。
  4. 然后返回对新值的引用。

第 3 步与 constness 不兼容。 而不是有两个 不同功能的运算符[] 重载,语言迫使你 对 const 对象使用 map::find。

【讨论】:

  • 就是这样!!我会在 7 分钟内标记为已回答,不知道为什么我不能...如果答案是正确的那就是正确的 :)
  • 现在可能值得一提std::map::at
【解决方案2】:

[] 的原型是

 data_type& operator[](const key_type& k)

即一个非 const 操作,所以你不能从一个 const 成员函数的成员上调用它。

您可以将代码更改为:

std::map<...>::const_iterator where = m_egressCandidatesByDestAndOtMode.find(tt);
if (egressCandidatesByDestAndOtMode.end() != where) {
    const vector<set<int>>& temp = where->second;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 2023-03-30
    • 2010-09-13
    • 2016-02-01
    • 2020-05-09
    • 2012-11-19
    相关资源
    最近更新 更多