template <typename ValueType> ValueType* RadixTree<ValueType>::search(std::string key) const {
typename std::map<std::string, ValueType>::const_iterator it = radixTree.find(key);
if (it == radixTree.end())
return nullptr;
return &(it->second);
}
你好!以上是我的代碼,它是我的 radixTree 實作的占位符。我不明白為什么我需要在第二行的 std::map 之前輸入型別名,以及為什么 &(it->second) 最終會回傳一個 const_Ty2*。我認為在這種情況下, const_Ty2 和 ValueType 是等價的。該變數radixTree當前是一個 Map,雖然我想用我的 radixTree 實作替換它,但我也想了解我現在遇到的問題。任何幫助將不勝感激。謝謝!
跟進:我也遇到了這個方法的問題
template <typename ValueType> void RadixTree<ValueType>::insert(std::string key, const ValueType& value) {
radixTree.insert(key, value);
}
并且 radixTree 被宣告為
std::map<std::string,ValueType> radixTree;
這個方法給了我一個很長的錯誤,我不太明白。
std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const std::string,ValueType>>>> std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::insert(std::_Tree_const_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const std::string,ValueType>>>>,std::pair<const std::string,ValueType> &&)': cannot convert argument 1 from 'std::string' to 'std::_Tree_const_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const std::string,ValueType>>>>
有人也可以幫助我嗎?再次感謝你!
uj5u.com熱心網友回復:
您的函式是 const 并且您正確使用了 const_iterator。這意味著它it->second也是const。當你這樣做時&it->second,它會變成一個 const 指標,它不能被隱式轉換為非 const 指標(這種轉換會丟棄 const 限定符)。
目前還不清楚為什么你想要一個指向內部值的非常量指標。我不得不假設這是一個錯誤。您應該將回傳型別更改為const ValueType*.
關于您剛剛對問題所做的編輯:
radixTree.insert(key, value);
該訊息告訴您函式引數錯誤。檢查插入功能的檔案。你會發現它需要 a value_typewhich is a std::pair<const Key, T>。錯誤的有用部分在這里:
無法將引數 1 從 'std::string' 轉換為 'std::_Tree_const_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const std::string,ValueType>>>>
它試圖匹配一個有兩個引數的呼叫,多載決議試圖將其決議為insert(const_iterator hint, const value_type &value). 這應該告訴你出了點問題。
嘗試這個:
radixTree.insert(std::make_pair(key, value));
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/440067.html
上一篇:使用模板鏈接串列類復制建構式錯誤:沒有匹配函式呼叫“Node<int>::Node()”
下一篇:沒有物件切片的多型向量[C ]
