在C ++中,有没有办法编写一个智能指针数组,它们会自动使用数组中的索引更新指向的值?指向的值具有存储索引的成员,类似于侵入式引用。
我有兴趣编写一个具有可更新优先级的堆。如果堆中的值总是更新为指向堆存储中的索引,而在堆算法内部没有特殊知识的情况下,在更改值的优先级时,很容易将该链接返回到堆中。知道了更改项的位置后,可以快速恢复堆不变量。
答案 0 :(得分:0)
这是我尝试基本实现的。我宁愿参数化Container
对全局数组的引用,而不会使实例大于一个指针,这样可以提高安全性。如果它也是一个随机访问迭代器,那将会更有用。
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;
}