我正打算寫C++中的記憶模式,結束了以下辦法LAMBDA捕捉價值強制所有範圍的對象爲const
std::function<int(int)> Memoize(std::function<int(int)> fn)
{
std::map<int, int> memo;
std::function<int(int)> helper = [=](int pos)
{
if (memo.count(pos) == 0)
{
memo[pos] = fn(pos);
}
return memo[pos];
};
return helper;
}
奇怪的是,我的編譯器VS 2012,拒絕與以下編譯錯誤
1>Source1.cpp(24): error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const std::map<_Kty,_Ty>' (or there is no acceptable conversion)
在我看來,編譯器故意將值作爲一個const對象捕獲所有東西。我無法找到任何有關此行爲的記錄參考。
任何人都可以幫助我理解這裏可能發生的事情嗎?
不應該是'memo.count(pos)'?就目前而言,對於0以外的任何值,我們總是計算並存儲該值,即使它已經存在。 – 2014-10-31 08:51:31
@PhilWright:是的,沒錯。其實我試圖調試我的代碼,而發佈忘記改變它。感謝您強調它。 – Abhijit 2014-10-31 09:15:51