我在这里遇到了一些难题。我正在写一个网格(网格)生成器。在这样做时,我需要从较高维元素获得较低维元素的列表(即,“三角形”元素由3“行”元素组成)。我需要唯一的行元素列表,我需要父元素来存储指向每个独特子元素的指针。
为此,我创建了一个std :: set指向子元素的智能指针,并尝试将每个子元素插入到列表中。每次我尝试插入一个元素时,我都会要求一个包含预先存在元素的迭代器的对,以及一个指定元素是否已插入的布尔值。
问题是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;
}
答案 0 :(得分:0)
这里根本不需要演员表。
std::set<K, Comp>::iterator
与std::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)
。