本文介绍了C ++映射-自引用迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以声明其值类型为其自身迭代器的std::map?

Is there a way to declare a std::map whose value type is an iterator to itself?

map<string, map<string, (#)>::iterator> myMap;

上面的代码段不起作用,因为迭代器类型需要知道第二个模板参数,标记为(#). (本身就是这样).

The above code snippet wouldn't work because the iterator type needs to know the second template argument, marked as (#). (which would be itself).

目的是避免进行不必要的find操作来访问另一个元素指向的元素—.而不是使用map<string, string>.

The intent is to avoid doing unnecessary find operations to access the element that is pointed to by another element — as opposed to using map<string, string>.

推荐答案

这种定义是不可能的,因为值类型和迭代器类型将是相互无限递归的.

Such definition is not possible, since the value type and the iterator type would be mutually infinitely recursive.

可以使用一些间接方法来解决此问题.甚至有可能避免动态分配std::any,除非V完整,否则std::map<K,V>是不确定的.

It is possible to work around this using a bit of indirection. It is even possible to avoid the dynamic allocation of std::any, and the fact that std::map<K,V> is undefined unless V is complete.

但是解决方案有点棘手,它依赖于一些合理的假设,但标准并未对此做出规定.请参阅实施中的注释.主要技巧是将成员变量类型的定义推迟到信封类定义之后.这是通过重新使用原始存储来实现的.

But the solution is a bit tricky, and relies on some assumptions which are reasonable, but not specified by the standard. See comments in the implementation. The main trick is to defer definition of a member variable type until after definition of the enveloping class. This is achieved by reusing raw storage.

首先使用:

int main()
{
    Map map;
    auto [it, _] = map.emplace("first", iter_wrap{});
    map.emplace("maps to first", conv::wrap(it));
    // erase first mapping by only looking
    // up the element that maps to it
    map.erase(conv::it(map.find("maps to first")));
}

定义

struct NoInitTag {} noInitTag;

class iter_wrap
{
public:
    iter_wrap();
    ~iter_wrap();
    iter_wrap(const iter_wrap&);
    iter_wrap(iter_wrap&&);
    const iter_wrap& operator=(const iter_wrap&);
    const iter_wrap& operator=(iter_wrap&&);

private:
    // We rely on assumption that all map iterators have the same size and alignment.
    // Compiler should hopefully warn if our allocation is insufficient.
    using dummy_it = std::map<int, int>::iterator;
    static constexpr auto it_size = sizeof(dummy_it);
    static constexpr auto it_align = alignof(dummy_it);
    alignas(it_align) std::byte store[it_size];

    explicit iter_wrap(NoInitTag){}
    friend struct conv;
};

using Map = std::map<std::string, iter_wrap>;
using It = Map::iterator;

struct conv {
    static constexpr It&
    it(iter_wrap&& wrap) noexcept {
        return *std::launder(reinterpret_cast<It*>(wrap.store));
    }
    static constexpr const It&
    it(const iter_wrap& wrap) noexcept {
        return *std::launder(reinterpret_cast<const It*>(wrap.store));
    }
    template<class It>
    static const iter_wrap
    wrap(It&& it) {
        iter_wrap iw(noInitTag);
        create(iw, std::forward<It>(it));
        return iw;
    }
    template<class... Args>
    static void
    create(iter_wrap& wrap, Args&&... args) {
        new(wrap.store) It(std::forward<Args>(args)...);
    }
    static constexpr void
    destroy(iter_wrap& wrap) {
        it(wrap).~It();
    }
};

iter_wrap::iter_wrap() {
    conv::create(*this);
}
iter_wrap::iter_wrap(const iter_wrap& other) {
    conv::create(*this, conv::it(other));
}
iter_wrap::iter_wrap(iter_wrap&& other) {
    conv::create(*this, std::move(conv::it(other)));
}
const iter_wrap& iter_wrap::operator=(const iter_wrap& other) {
    conv::destroy(*this);
    conv::create(*this, conv::it(other));
    return *this;
}
const iter_wrap& iter_wrap::operator=(iter_wrap&& other) {
    conv::destroy(*this);
    conv::create(*this, std::move(conv::it(other)));
    return *this;

}
iter_wrap::~iter_wrap() {
    conv::destroy(*this);
}


旧答案;假定在遍历存储的映射时避免查找不是一个重要功能.


Old answer; This assumed that it was not an important feature to avoid lookups while traversing stored mappings.

看来,您尝试表示的数据结构是一组键(字符串),其中每个键都映射到该组的另一个键.表示这一点的更简单方法是将这两个方面分开:

It appears that the data structure that you attempt to represent is a set of keys (strings), where each key maps to another key of the set. Easier way to represent that is to separate those two aspects:

using Set = std::set<std::string>;
using Map = std::map<Set::iterator, Set::iterator>;

请注意,这两个数据结构不会自动保持同步.添加到集合中的元素不会自动映射到另一个元素,而从集合中删除的元素会将悬空的迭代器留给地图.因此,编写自定义容器类以强制必要的不变性是明智之举.

Note that these two data structures do not automatically stay in sync. An element added to the set doesn't automatically have a mapping to another, and an element erased from the set leaves dangling iterators to the map. As such, it would be wise to write a custom container class that enforces the necessary invariants.

这篇关于C ++映射-自引用迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 09:35