【问题标题】:unordered_map.emplace giving compiler time errors?unordered_map.emplace 给出编译器时间错误?
【发布时间】:2016-12-25 00:28:56
【问题描述】:

我有这个容器作为一个类的成员:

std::unordered_map<std::string, Fruit> m_fruits;

我想在同一个类中添加一个新元素,我尝试了两种方法,两种方法都应该基于示例工作。 (在 emplace 的页面上)但是在某个地方我犯了一个错误。 (fruitName 是一个 const std::string&

m_fruits.emplace(fruitName, Fruit());

错误 C2660 'std::pair::pair': 函数不接受 2 个参数

m_fruits.emplace(std::make_pair(fruitName, Fruit()));

错误 C2440 '':无法从 'initializer 转换 列表”到“_Mypair”

水果类:

class Fruit {

public:
    Fruit(); 
    Fruit(const Fruit& fruit) = delete;
    Fruit operator=(const Fruit& fruit) = delete;
    virtual ~Fruit();
};

更新:

我发现我不应该删除fruit的默认复制构造函数。

但我不明白。 emplace 不是用于将对象构造到容器中而不是在容器外部创建对象然后将其复制到容器中吗?

如果容器中没有带有键的元素,则使用给定的参数就地将新元素插入到容器中。

请有人解释为什么我需要一个复制构造函数来使用这个方法。 谢谢!

【问题讨论】:

  • 你能提供一个minimal reproducible example吗?只需对Fruit 使用虚拟声明,例如struct Fruit {};_Mypair 也很可疑,它看起来不像标准的 c++ 实现。
  • m_fruits[fruitName] = Fruit();怎么样
  • @πάνταῥεῖ -- _Mypair 绝对是一种广泛使用的标准库实现的风格。
  • @Pete 好吧,虽然命名很愚蠢。
  • @πάνταῥεῖ -- 叹息。

标签: c++ c++11 dictionary containers


【解决方案1】:

这就是 std::pair 代码的作用

_LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR_AFTER_CXX11
    pair(const _T1& __x, const _T2& __y)
         : first(__x), second(__y) {}

根据上面的代码,参数是从复制或移动构造函数构造的。因此,您需要其中之一。

Fruit 类没有定义复制构造函数或移动构造函数。在这里,m_fruits.emplace(fruitName, Fruit()) 编译器生成临时 Fruit 对象,该对象必须在地图内复制构造或移动构造。由于 Fruit 类的复制构造函数被删除并且没有移动构造函数,因此它给出了编译器错误。 有两种方法可以消除此错误

1) 引入移动构造函数

Fruit(Fruit && other) {
}

2) 或者不要删除拷贝构造函数,而是定义拷贝构造函数

水果(常量水果和其他){ }

这是工作的sn-p

#include <iostream>
#include <unordered_map>

class Fruit {
public:
    Fruit() {}
    Fruit(const Fruit& fruit) {
    }
    Fruit operator=(const Fruit& fruit) = delete;
    ~Fruit() {}
};

int main() {
    std::unordered_map<std::string, Fruit> m_fruits;

    m_fruits.emplace("apple", Fruit());
    m_fruits.emplace(std::make_pair("orange", Fruit()));
    for (const auto & e: m_fruits) {
       std::cout << "key=" << e.first << std::endl;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 2023-03-26
    • 2012-07-22
    • 1970-01-01
    相关资源
    最近更新 更多