gpt4 book ai didi

c++ - std::map,double>> 中的 "Forced constness"?

转载 作者:行者123 更新时间:2023-11-30 01:00:25 25 4
gpt4 key购买 nike

考虑这个程序:

#include <map>
#include <vector>
typedef std::vector<int> IntVector;
typedef std::map<IntVector,double> Map;
void foo(Map& m,const IntVector& v)
{
Map::iterator i = m.find(v);
i->first.push_back(10);
};
int main()
{
Map m;
IntVector v(10,10);
foo(m,v);
return 0;
}

使用g++ 4.4.0,我得到了他的编译错误:

test.cpp: In function 'void foo(Map&, const IntVector&)':
test.cpp:8: error: passing 'const std::vector<int, std::allocator<int> >' as 'this' argument of 'void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = int, _Alloc = std::allocator<int>]' discards qualifiers

如果我在 foo 中使用 Map::const_iterator 而不是使用非 const 迭代器,我预计会出现此错误。

我错过了什么,为什么会出现此错误?

最佳答案

映射中的键是常量。 map 是一棵树,您不能四处更改键,否则会破坏其不变量。 value_type map 的 KeyValuestd::pair<const Key, Value> , 以强制执行此操作。

您的设计需要一些改变。如果确实需要修改key,则需要移除元素,更改其key,并用新的key重新插入。

还特别针对您的示例,您将得到未定义的行为(如果这确实有效)。当您调用 foo 时,您的 map 是空的, 所以 find 返回的迭代器将是 m.end() ;该元素不存在。但随后您将继续修改这个不存在的元素:ka-boom。每当你find一些东西,你应该在尝试使用它之前检查它是否被发现。

关于c++ - std::map<std::vector<int>,double>> 中的 "Forced constness"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2696754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com