【发布时间】:2019-06-25 14:35:16
【问题描述】:
这里的const是编译问题的原因。但是,我自己实现了 AVL 树,我不明白为什么。
代码如下:
#include <set>
int main ()
{
int a;
// I want the set to carry the "promise"
// to keep the pointers constant
std::set<int * const> x;
x.insert(&a);
}
这是错误:
In file included from /usr/include/c++/7/string:48:0,
from /usr/include/c++/7/bits/locale_classes.h:40,
from /usr/include/c++/7/bits/ios_base.h:41,
from /usr/include/c++/7/ios:42,
from /usr/include/c++/7/ostream:38,
from /usr/include/c++/7/iostream:39,
from demo.cpp:1:
/usr/include/c++/7/bits/stl_function.h: In instantiation of ‘struct std::_Identity<int* const>’:
/usr/include/c++/7/bits/stl_tree.h:2091:29: required from ‘std::pair<std::_Rb_tree_iterator<_Val>, bool> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_insert_unique(_Arg&&) [with _Arg = int* const; _Key = int* const; _Val = int* const; _KeyOfValue = std::_Identity<int* const>; _Compare = std::less<int* const>; _Alloc = std::allocator<int* const>]’
/usr/include/c++/7/bits/stl_set.h:510:48: required from ‘std::pair<typename std::_Rb_tree<_Key, _Key, std::_Identity<_Key>, _Compare, typename __gnu_cxx::__alloc_traits<_Alloc>::rebind<_Key>::other>::const_iterator, bool> std::set<_Key, _Compare, _Alloc>::insert(std::set<_Key, _Compare, _Alloc>::value_type&&) [with _Key = int* const; _Compare = std::less<int* const>; _Alloc = std::allocator<int* const>; typename std::_Rb_tree<_Key, _Key, std::_Identity<_Key>, _Compare, typename __gnu_cxx::__alloc_traits<_Alloc>::rebind<_Key>::other>::const_iterator = std::_Rb_tree_const_iterator<int* const>; std::set<_Key, _Compare, _Alloc>::value_type = int* const]’
demo.cpp:11:18: required from here
/usr/include/c++/7/bits/stl_function.h:877:7: error: ‘const _Tp& std::_Identity<_Tp>::operator()(const _Tp&) const [with _Tp = int* const]’ cannot be overloaded
operator()(const _Tp& __x) const
^~~~~~~~
/usr/include/c++/7/bits/stl_function.h:873:7: error: with ‘_Tp& std::_Identity<_Tp>::operator()(_Tp&) const [with _Tp = int* const]’
operator()(_Tp& __x) const
有没有一种“干净”的方式来做到这一点? (即,不是一种解决方法,比如为这种情况创建一个带有比较器的“指针类”)
【问题讨论】:
-
const int* != int* const -
是的。我知道吗?
-
我指出这一点是因为
int* const是一个无法更改的值,这意味着std::set的任何内部结构都不能复制构造或分配,这违反任何 STL 集合的要求。您想防止更改指向的数据,但存储无法更改的指针没有意义,因为您不直接使用内部结构。 -
我很困惑,集合中的元素cannot be modified,这是您正在寻找的保证
标签: c++ pointers constants stdset