std::set迭代器的Const_pointer_cast
const_pointer_cast of a std::set iterator
我在这里遇到了一个难题。我正在写一个网格(网格)生成器。在这样做时,我需要从高维元素中获得低维元素的列表(即一个"三角形"元素由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>::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)
相关文章:
- 如何理解C++标准N3337中的expr.const.cast子句8
- C++ - "!pointer"和"pointer == nullptr"的区别?
- C++Cast运算符过载
- "No-Const Pointer to Const "调用功能
- "owned pointer"和 std::shared_ptr 的"stored pointer"有什么区别?
- 删除分配的 (?) 指针时"Pointer being freed was not allocated"
- 错误:"cast"未命名类型void setCastDescription(std::string
- C++ 中的构造函数、继承、堆栈、堆、this-pointer 和段错误
- "Called Object Type is Not a Function or Pointer" 与 typedef 和类
- 通过使用 const-cast 的非常量引用来延长临时的寿命
- 马洛克会在 C++17 年返回"invalid pointer value"吗?
- "(void) cast"与功能有什么区别 "__attributes__"来沉默未使用的参数警告?
- c++为什么decltype(*pointer)会产生引用
- 指向对象生存期之外的已分配内存的指针是"invalid pointer[s]"还是"pointer[s] to an object"?
- 为什么"non-standard syntax; use '&' to create a pointer to member"在 CTOR 中使用线程?
- Golang CGO with large char pointer语言 - SEGSERV
- 向量<pointer>:插入(迭代器,指针)插入垃圾值
- 为什么选择 g++ 给予者:"error: cast to pointer from integer of different size [-Werror=int-to-pointer-cast]"
- 禁用 Clang 中的"cast from pointer to smaller type uint32_t"错误
- 为什么铸造长可以解决"warning: cast to pointer from integer of different size"?