1 c++
考虑这个程序:
#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;
}
Run Code Online (Sandbox Code Playgroud)
使用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
Run Code Online (Sandbox Code Playgroud)
如果我Map::const_iterator在foo 中使用但不使用非const迭代器,我会期望这个错误.
我错过了什么,为什么我会收到此错误?
地图中的键是不变的.地图是一棵树,你不仅可以绕过改变键,也可以打破它的不变量.该value_type地图的使用Key,并Value是std::pair<const Key, Value>,执行此操作.
您的设计需要一些变化.如果确实需要修改密钥,则需要删除该元素,更改其密钥,然后使用新密钥重新插入该密钥.
同样关于你的例子,你会得到未定义的行为(如果这确实有效).你打电话时你的地图是空的foo,所以返回的迭代器find将是m.end(); 该元素不存在.但接下来你会继续修改这个不存在的元素:ka-boom.无论何时find,只要您尝试使用它,就应该检查它是否已找到.
| 归档时间: |
|
| 查看次数: |
498 次 |
| 最近记录: |