为什么需要使用unordered_map和tuple的默认构造函数? [英] Why a default constructor is needed using unordered_map and tuple?

查看:121
本文介绍了为什么需要使用unordered_map和tuple的默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的程序中,我将一些信息存储在哈希表(std :: unordered_map)中,键是RectData类的对象,关联的值是元组< uint,RectData,enum>和自定义KeyHash和KeyEqual已定义。

In the program below, I store some information in an hash table (std::unordered_map), the key is an object of the class RectData, the associated value is a tuple <uint, RectData, enum> and custom KeyHash and KeyEqual have been defined.

插入<键,值>对没有默认构造函数的情况下,使用gcc 4.9.2会产生两页错误。出现第一个错误的行是:

Inserting a <key,value> pair without a default constructor gives two pages of error with gcc 4.9.2. The line with the first error is:

visited_info[rect0] = info0;

我使用MSVC ++ 12.0进行了两次检查,我也收到错误消息。

I double checked with MSVC++ 12.0, I also have error messages.

当我添加默认构造函数时,编译正常,并且在运行时调用默认构造函数。我不明白为什么RectData类需要默认的构造函数?

When I add the default constructor, compilation is ok and the default constructor is called at run time. I could not understand why a default constructor is needed for the class RectData ?

使用[]运算符从哈希表中检索数据,在编译时也需要默认的构造函数时间,但在运行时未调用,为什么?

Retrieving data from the hash table, using the [] operator, also requires a default constructor at compile time, but it is not called at run time, why ?

auto info = visited_info[rect];

注意:使用Visited_info.emplace()和Visited_info.find()更改代码可以解决此问题,

Note: Changing the code with visited_info.emplace() and visited_info.find() solves the problem, but does not answer the question.

谢谢您的回答。

完整代码如下。

#include <boost/functional/hash.hpp>
#include <tuple>
#include <vector>
#include <unordered_map>
#include <iostream>

using uint = unsigned int;

enum class Direction : int { left = 0, right = 1, up = 2, down = 3, null = 4 };

class RectData {
 public:
  RectData(uint width, uint height)
      : width_(width), height_(height), datas_(width * height, 0) {
    total_ = width_ * height_;
  }


  // A default constructor must be defined!
  RectData() : RectData(0u, 0u) {
    std::cout << "Calling the default constructor !!!" << std::endl;
  }

  size_t hash() const {
    return boost::hash_value(datas_);
  }

  bool operator==(const RectData &rect) const {
    return (width_ == rect.width_) &&
           (height_ == rect.height_) &&
           (datas_ == rect.datas_);
  }

  struct KeyHash {
    std::size_t operator()(const RectData &rect) const {
      return rect.hash();
    }
  };

  struct KeyEqual {
    std::size_t operator()(const RectData &r1, const RectData &r2) const {
      return r1 == r2;
    }
  };

 private:
  uint width_;
  uint height_;
  std::vector<uint> datas_;
  uint total_;
};

using StoredInfo = std::tuple<uint, RectData, Direction>;

int main() {
  std::unordered_map<RectData, StoredInfo, RectData::KeyHash,
                     RectData::KeyEqual> visited_info;

  RectData rect0(5u, 5u);
  RectData rect1(4u, 4u);
  RectData rect2(3u, 3u);
  RectData rect3(2u, 2u);

  StoredInfo info0 = std::make_tuple(10u, rect1, Direction::up);
  StoredInfo info1 = std::make_tuple(11u, rect2, Direction::down);
  StoredInfo info2 = std::make_tuple(12u, rect3, Direction::left);
  StoredInfo info3 = std::make_tuple(13u, rect0, Direction::right);


  // the line below requires a default RectData constructor!!! 
  visited_info[rect0] = info0;

  // default RectData constructor also needed here !!!
  visited_info[rect1] = std::move(info2);

  // but not needed here
  visited_info.insert(std::make_pair(rect2, info2));

  // and not needed here
  visited_info.emplace(rect3, info3);

  // but needed here and not called!!! 
  StoredInfo i1 = visited_info[rect1];
  std::cout << "Verify (must be 11) = " << std::get<0>(i1)
            << std::endl;

  // but needed here and not called!!! 
  StoredInfo &i2 = visited_info[rect2];
  std::cout << "Verify (must be 12) = " << std::get<0>(i2)
            << std::endl;


  // and not needed here
  auto it = visited_info.find(rect3); 
  std::cout << "Verify (must be 13) = " << std::get<0>(it->second)
            << std::endl;

}


推荐答案

visited_info[rect0] = info0;

那么,您认为这是什么呢?左侧评估为记录明确的到存储在地图中的项目。如果该项目以前不存在,则默认为默认构造。

well, what do you think this does? It's well-documented that the left-hand side evaluates to a reference to an item stored in the map. If that item wasn't there before, it is default constructed first.

然后,您可以使用复制或移动分配从右侧更新该默认结构的项目。

You then use either copy- or move-assignment to update that default-constructed item from the right-hand-side of the expression.

如果要避免使用默认的构造和分配操作,请使用放置

If you want to avoid the default-construct-and-assign operation you're getting now, use emplace instead.

NB。例如,Python可能是造成混乱的原因,其中 MyObj [1] 可能会转换为 __ getitem __ 调用,但 MyObj [1] = 1 __ setitem __ 呼叫。

NB. One possible source of confusion is, for example, Python, where MyObj[1] might translate to a __getitem__ call, but MyObj[1]=1 to a __setitem__ call.

在C ++中,左侧表达式和右侧表达式都必须求值为 something ,而无需了解它们所处的语句。因此,左侧表达式边评估为您可以从中读取或分配给它的引用-但是该对象必须存在,然后才能获取该引用。

In C++, both the left-hand-side and right-hand-side expressions must evaluate to something, without knowing anything about the statement they're in. Hence, the left-hand-side evaluates to a reference which you can either read from or assign to - but the object needs to exist before you can take that reference.

这篇关于为什么需要使用unordered_map和tuple的默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆