【发布时间】:2020-01-11 01:01:22
【问题描述】:
我正在尝试为哈希表创建一个包含唯一指针的类,但每当我尝试向表添加指针时,我都会收到一个错误,该错误指向与我正在使用的库不同的文件。
我尝试使用.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>,_Alloc,false>>::insert(std::_List_const_iterator>>,const 标准::对>> &)': 无法将参数 1 从 'int' 转换为 'std::_List_const_iterator>>'
使用table.insert 或table.emplace(std::make_pair(tailPointer, itemPtr)) 时文件实用程序出错:
C2440:“”:无法从“初始化列表”转换 到“_MyPair”
【问题讨论】:
-
Table.emplace(tailPointer, itemPtr)->Table.try_emplace(tailPointer, std::move(itemPtr))(但 C++17)。 -
tailPointer++;后跟return tailPointer--;让我有点困惑...... -
Jarods 修复确实有效,非常感谢。
标签: c++ c++11 unordered-map