std::set迭代器的Const_pointer_cast

const_pointer_cast of a std::set iterator

本文关键字:pointer cast Const set 迭代器 std      更新时间:2023-10-16

我在这里遇到了一个难题。我正在写一个网格(网格)生成器。在这样做时,我需要从高维元素中获得低维元素的列表(即一个"三角形"元素由3个"线"元素组成)。我需要唯一的行元素列表,并且需要父元素存储指向其每个唯一子元素的指针。

为此,我创建了一组指向子元素的智能指针,并尝试将每个子元素插入到列表中。每次尝试插入一个元素时,我都要求使用一对,其中包含一个指向已有元素的迭代器和一个指定元素是否已插入的布尔值。

问题在于std::set(和map)返回指向预先存在元素的常量迭代器。但是,我需要给元素的父元素,我没有插入一个指向先前存在的元素的非常量指针。因此,我使用const_pointer_cast<>将常量迭代器强制转换为非常量迭代器。

有更好的方法来做这件事吗?使用const_pointer_cast()可能并不理想。我应该在这个应用程序中使用一些东西来代替std::set吗?

编辑:函数如下:

template<class T1, class T2>
int getUniqueSubelements(std::set<std::shared_ptr<T1>, elGreater>& elements,
                         std::set<std::shared_ptr<T2>, elGreater>& childels)
{
    typedef std::shared_ptr<T2> child_ptr;
    std::pair<typename std::set<child_ptr, elGreater>::iterator, bool> ret;
    for (auto parit = elements.begin(); parit != elements.end(); ++parit)
    {
        (*parit)->generateChildren();
        const std::vector<child_ptr>& children = (*parit)->getChildren();
        for (int i = 0; i < children.size(); i++)
        {
            ret = childels.insert(children[i]);
            if (ret.second == false)
            {
                child_ptr temp = std::const_pointer_cast<T2>(*ret.first);
                bool orient = elOrientation(children[i], temp);
                children[i]->swapInParent(temp, orient);
            }
        }
    }
    return 1;
}

这里根本不需要强制转换。

确实,std::set<K, Comp>::iteratorstd::set<K, Comp>::const_iterator相同,并且iterator::operator*返回const K&

但在您的情况下,这意味着*ret.first的类型是const std::shared_ptr<T2>&。这是(T2* const)的模拟,而不是(const T2*):你不能修改智能指针,但你可以修改实际存储的对象。

假设elOrientation类似于

template <typename T>
bool elOrientation(std::shared_ptr<T>, std::shared_ptr<T>);

你可以直接调用elOrientation(children[i], *ret.first)