【问题标题】:How I can define a list of map::iterator and map of list::iterator如何定义 map::iterator 列表和 list::iterator 映射
【发布时间】:2016-03-31 23:20:42
【问题描述】:

我需要一个 Map::iterator 列表和 List::iterator 映射。我该怎么做:

typedef std::list<Map::iterator> List;
typedef std::map<int, List::iterator> Map;

也许我可以对迭代器使用前向声明之类的东西?

【问题讨论】:

  • 听起来像一个递归定义。您确定这是您问题的正确解决方案吗?你想解决什么问题?
  • 我确定。如果我只使用普通指针,那不是问题,因为我可以制作前向声明结构/类。在这种情况下,我想使用像普通指针这样的迭代器。
  • 因此,您将拥有一个 Map,当给定 Int 时,将返回一个 iterator 到一个 List,它包含一个 iterator 到一个 Map,它包含和 @ 987654327@ 到“列表”...等等。也许您的解决方案是 3 种不同的类型?
  • 一种可能的解决方案是使用类型擦除,例如将第二个参数设为boost::any
  • @PazO 我上面问题中的代码是一个简单的例子,仅用于说明问题。

标签: c++ list dictionary iterator std


【解决方案1】:

这样的事情应该可以帮助你:

#include <cassert>
#include <iostream>
#include <list>
#include <map>
#include <string>

struct decl_t {
    typedef std::map<std::string, decl_t> map_t;
    typedef std::list<std::pair<int, typename map_t::iterator>> list_t;

    list_t::iterator it;
};

int main(int argc, const char* argv[])
{
    decl_t::map_t map;
    decl_t::list_t list;

    auto list_it = list.emplace(list.end(), 42, decl_t::map_t::iterator());
    const auto pair = std::make_pair(std::string("key"), decl_t{list_it});
    auto result = map.insert(pair);
    assert(result.second);
    auto map_it = result.first;
    list_it->second = map_it;

    std::cout << list_it->second->first << std::endl;
    std::cout << map_it->second.it->first << std::endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    • 2012-11-23
    • 2017-04-21
    • 1970-01-01
    相关资源
    最近更新 更多