gpt4 book ai didi

c++ - 如何修复 'no overloaded function takes 2 arguments' 错误 C++

转载 作者:行者123 更新时间:2023-11-28 04:10:42 39 4
gpt4 key购买 nike

我正在尝试为哈希表创建一个包含唯一指针的类,但每当我尝试向该表添加一个指针时,我都会收到一个错误,该错误指向我正在使用的库中的不同文件。

我试过使用 .insert() 而不是 .emplace()。我试过传递一对 key 和指针。

这两个都导致了与原来不同的错误

这是 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': no overloaded function takes 2 arguments

使用 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>> &)': cannot convert argument 1 from 'int' to 'std::_List_const_iterator>>'

使用 table.inserttable.emplace(std::make_pair(tailPointer, itemPtr)) 时文件实用程序出错:

C2440: '': cannot convert from 'initializer list' to '_MyPair'

最佳答案

解决问题的多种方法:

解决方案一:

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;
};

解决方案二:

int addItem(T newItem) {
Table.insert(std::make_pair(tailPointer++, std::make_unique<T>(newItem)));
return tailPointer;
}

方案三:

int addItem(T newItem) {
Table[tailPointer++] = std::make_unique<T>(newItem);
return tailPointer;
}

上述解决方案都不需要 C++ 17。所有解决方案都来自 C++11。您应该了解为什么会出现编译错误。使用您现有的代码,您正在尝试分配或复制不允许的 unique_ptr。它只能被移动。这就是您的编译器试图告诉您的内容。

关于c++ - 如何修复 'no overloaded function takes 2 arguments' 错误 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57850995/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com