【问题标题】:Recursive Standard C++ Library Container Types?递归标准 C++ 库容器类型?
【发布时间】:2021-02-19 03:59:21
【问题描述】:

是否可以这样定义标准 C++ 库容器类型 UM、OM 和 L:

  • UM 是一个 std::unordered_map 与 key_type int 和 mapped_type 迭代器到 OM
  • OM 是一个 std::map 与 key_type int 和 mapped_type L
  • L 是 UM 的迭代器 std::list

?

【问题讨论】:

  • 很确定答案是否定的。你也许可以通过前向声明和指针来解决这个问题。
  • 感谢@NathanOliver,您是正确的前向声明解决方案;但是要使用它,我需要重新实现这 3 个容器,这很烦人,因为所有 3 个容器的迭代器都被定义为指针(在我使用的 C++ 实现中);但我不能直接使用它们,因为我不能前向声明它们的内部节点类。所以只是想检查我是否遗漏了一些明显的解决方案。
  • 能否请您透露一下您要使用此数据结构解决什么问题?
  • @Bob__ 只需要管理许多具有 int 唯一 ID 的对象的集合,这些对象属于多个有序级别。一个级别可能会改变;那么它的所有对象仍应附加到更改的级别。需要处理一些查询,例如“找到包含给定集合中对象的大于 x 的最低级别”,还有一些其他查询。

标签: c++ types containers


【解决方案1】:

类似这样的:

#include <unordered_map>
#include <map>
#include <list>

struct Container{
  struct List;
  using OM = std::map<int, List>;
  using UM = std::unordered_map<int, typename OM::iterator>;
  using L = std::list<typename UM::iterator>;
  struct List{
    L l;
  };
  UM um;
  OM om;
  L l;
};

int main() {
  Container c;
  c.om[0] = Container::List();
  c.um[0]=c.om.begin();
  c.l.push_back(c.um.begin());
}

【讨论】:

  • 请注意,此代码在技术上具有未定义的行为:stackoverflow.com/questions/12281274/…
  • 我认为在 std::map 的情况下,一个完整的具有值的节点在调用方法之前实际上并没有被实例化。
猜你喜欢
  • 1970-01-01
  • 2021-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多