[英]How to fix 'no overloaded function takes 2 arguments' error C++
我正在嘗試為哈希表創建一個包含唯一指針的類,但是每當我嘗試向該表添加指針時,都會出現錯誤,該錯誤指向與我正在使用的庫不同的文件。
我嘗試使用.insert()
而不是.emplace()
。 我嘗試傳遞一對鍵和指針。
兩者都導致了與原始錯誤不同的錯誤
這是Hash_Table類:
///<summary>
/// A struct for a hash table
///</summary>
template <typename T>
struct Hash_Table
{
public:
///<summary>
/// Add an item to the hash table & return the item key
///</summary>
int addItem(T newItem) {
// Make the item into a unique pointer
std::unique_ptr<T> itemPtr = std::make_unique<T>(newItem);
//std::pair<int, std::unique_ptr<T>> pair = std::make_pair(tailPointer, itemPtr);
while (!Table.emplace(tailPointer, itemPtr).second) {
tailPointer++;
//pair.first++;
}
tailPointer++;
return tailPointer--;
};
private:
///<summary>
/// The actual hash table
///</summary>
std::unordered_map<int, std::unique_ptr<T>> Table;
///<summary>
/// Points to the key of the last item added to the hash table
///</summary>
int tailPointer;
};
當我嘗試table.emplace()
時,問題發生在addItem()
函數中。
上面顯示的代碼文件xmemory中的錯誤:
C2661:'std :: pair :: pair':沒有重載函數需要2個參數
使用table.insert()
時文件HashTable.h中的錯誤:
C2664:'std :: _ List_iterator >> std :: _ Hash>,std :: _ Uhash_compare <_Kty,_Hasher,_Keyeq>,_ Alloc,false >> :: insert(std :: _ List_const_iterator>,const std :: pair >> &)':無法將參數1從'int'轉換為'std :: _ List_const_iterator >>'
使用table.insert
或table.emplace(std::make_pair(tailPointer, itemPtr))
時文件實用程序中的錯誤:
C2440:'':無法從``初始化列表''轉換為``_MyPair''
解決問題的多種方法:
解決方案1:
int addItem(T newItem) {
// Make the item into a unique pointer
std::unique_ptr<T> itemPtr = std::make_unique<T>(newItem);
// Unique_ptr doesn't have assignment operator instead it has move-assignment.
// So it need to be moved only
std::pair<int, std::unique_ptr<T>> pair = std::make_pair(tailPointer++, std::move(itemPtr));
// For same above reason, it must be moved
Table.insert(std::move(pair));
return tailPointer;
};
解決方案2:
int addItem(T newItem) {
Table.insert(std::make_pair(tailPointer++, std::make_unique<T>(newItem)));
return tailPointer;
}
解決方案3:
int addItem(T newItem) {
Table[tailPointer++] = std::make_unique<T>(newItem);
return tailPointer;
}
以上解決方案均不要求C ++17。所有解決方案均來自C ++ 11。 您應該了解為什么會出現編譯錯誤。 使用您現有的代碼,您正在嘗試分配或復制不允許的unique_ptr。 它只能移動 。 這就是您的編譯器試圖告訴您的。
使用此方法,將解決c ++ 11中的unique_ptr問題
int addItem(T newItem) {
// Make the item into a unique pointer
while (!Table.emplace_hint(tailPointer, newItem).second) {
tailPointer++;
//pair.first++;
}
tailPointer++;
return tailPointer--;
};
謝謝Jarod42 ,您的修復工作成功了。
修復方法: Table.emplace(tailPointer, itemPtr)
-> Table.try_emplace(tailPointer, std::move(itemPtr))
(但是C ++ 17)。 -Jarod42
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.