如何解决“没有重载函数需要2个参数”错误C ++

时间:2019-09-09 09:12:41

标签: c++ c++11 unordered-map

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

我尝试使用.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;
};

当我尝试addItem()时,问题发生在table.emplace()函数中。

文件xmemory中的代码错误,如上所示:

  

C2661:'std :: pair :: pair':无重载函数   接受两个参数

使用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.inserttable.emplace(std::make_pair(tailPointer, itemPtr))时文件实用程序出错:

  

C2440:”:无法从“初始化程序列表”转换   到“ _MyPair”

3 个答案:

答案 0 :(得分:1)

多种解决问题的方法:

解决方案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。它只能移动。这就是编译器试图告诉您的。

答案 1 :(得分:0)

使用此方法,将解决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--;
};

答案 2 :(得分:0)

谢谢您Jarod42,您的修复工作成功了。

解决方法: Table.emplace(tailPointer, itemPtr)-> Table.try_emplace(tailPointer, std::move(itemPtr))(但C ++ 17)。 -Jarod42