簡體   English   中英

std :: map中的“強制常量” <std::vector<int> ,double&gt;&gt;?

[英]“Forced constness” in std::map<std::vector<int>,double> >?

考慮以下程序:

#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但未使用非常量迭代器,則會出現此錯誤。

我缺少什么,為什么會出現此錯誤?

映射中的鍵是恆定的。 地圖就是一棵樹,您不能只是四處更改鍵,否則就會破壞其不變性。 具有KeyValue的映射的value_typestd::pair<const Key, Value> ,以強制執行此操作。

您的設計需要進行一些更改。 如果確實需要修改密鑰,則需要刪除元素,更改其密鑰,然后使用新密鑰重新插入。

還要特別關注您的示例,您將獲得未定義的行為(如果這樣做確實可行)。 當您調用foo ,您的映射為空,因此find返回的迭代器為m.end() 元素不存在。 但是隨后您將繼續修改此不存在的元素:ka-boom。 無論何時find東西,都應在嘗試使用之前檢查是否已找到。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM