简体   繁体   English

是否可以有一个智能指针数组,该数组会自动用其索引更新其值?

[英]Is it possible to have an array of smart pointers that automatically updates its values with their index?

In C++, is there a way to write an array of smart pointers that automatically updates the pointed-to values with their index in the array? 在C ++中,有没有一种方法可以编写一个智能指针数组,该数组会自动使用它们在数组中的索引来更新指向的值? The pointed-to values have a member to store the index, similar to an intrusive refcount. 指向值具有一个成员来存储索引,类似于侵入引用计数。

I am interested in writing a heap with updatable priorities. 我对编写具有可更新优先级的堆感兴趣。 If the values in the heap were always updated to point to their index inside the heap storage, without special knowledge inside the heap algorithm, it would be easy to follow that link back into the heap when changing the value's priority. 如果堆中的值总是更新为指向堆存储中的索引,而在堆算法内部没有特殊知识,则在更改值的优先级时很容易将链接返回到堆中。 Knowing the position of the changed item, the heap invariant could then be quickly restored. 知道更改项的位置,然后可以快速恢复堆不变式。

This is my attempt at a basic implementation. 这是我尝试的基本实现。 I would prefer to parameterize Container s reference to the global array without making instances larger than one pointer, and it would be good to improve safety. 我宁愿在不使实例大于一个指针的情况下,将Container的引用参数Container全局数组,这对提高安全性是有益的。 It would be more useful if it was also a random access iterator. 如果它也是一个随机访问迭代器,它将更加有用。

class Contained {
    public:
        uintptr_t index;
};

class Container {
    public:
        Contained *value;

    Container& operator=(Container& other);
};

Container foobars[4];

Container& Container::operator=(Container& other) {
    this->value = other.value;
    this->value->index = ((uintptr_t)this - (uintptr_t)foobars) / sizeof(this->value);
    return *this;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM