我有一个用于存储数据的自定义容器和一个用于访问它的迭代器。问题是 - >迭代器中的运算符不允许我修改容器中的数据。
value_type是std :: pair<>
数据持有者:
template <class tree>
struct avl_node {
private:
typedef typename tree::key_type Key;
typedef typename tree::mapped_type Type;
typedef typename tree::value_type value_type;
public:
typedef avl_node* node_ptr;
typedef const avl_node* const_node_ptr;
node_ptr _parentNode, _leftNode, _rightNode;
int _balance;
Key first;
Type second;
}
迭代器:
template <class tree>
class avl_iterator {
public:
typedef typename tree::node node;
typedef typename tree::node_ptr node_ptr;
typedef typename tree::const_node_ptr const_node_ptr;
typedef typename tree::utilities utilities;
typedef typename tree::value_type value_type;
private:
node_ptr _node;
public:
avl_iterator() : _node() { }
avl_iterator( const node_ptr node ) : _node ( node ) { }
~avl_iterator() { _node = NULL; }
avl_iterator& operator=(const avl_iterator& rhs) {
_node = rhs._node;
return (*this);
}
bool operator == ( const avl_iterator& rhs ) { return ( _node == rhs._node); }
bool operator != ( const avl_iterator& rhs ) { return ( _node != rhs._node); }
avl_iterator& operator++()
{
_node = utilities::next_node( _node );
return (*this);
}
avl_iterator& operator ++( int ) {
avl_iterator temp(*this);
++(*this);
return(temp);
}
avl_iterator& operator -- () {
_node = utilities::prev_node( _node );
return (*this);
}
avl_iterator& operator -- ( int ) {
avl_iterator temp(*this);
--(*this);
return(temp);
}
value_type& operator * () {
return value_type( node->first, node->second );
}
node_ptr operator -> () const {
return _node;
}
};
主
try{
using namespace avl;
avltree<int,int> tree;
tree.insert(intPair(1,1));
tree.insert(intPair(2,1));
tree.insert(intPair(3,1));
tree.insert(intPair(4,1));
tree.insert(intPair(5,1));
tree.insert(intPair(6,1));
tree.insert(intPair(7,1));
tree.insert(intPair(8,1));
tree.insert(intPair(9,1));
tree.insert(intPair(10,1));
tree.insert(intPair(11,1));
tree.insert(intPair(12,1));
avltree<int,int>::iterator it;
//std::map<int,int>::iterator it;
for( it = tree.begin(); it != tree.end(); ++it )
{
std::cout<< it->first << " : ";
}
std::cout << std::endl;
for( it = tree.end(); it != tree.begin(); --it )
{
std::cout<< it->first << " : ";
}
std::cout << std::endl;
it->first = 5;//shouldnt compile with this line of code, but does
it->second = 10;
}
catch(...)
{
std::cout<<"Catch Block\n";
}
答案 0 :(得分:4)
最好有
value_type value;
在avl_node
而不是:
Key first;
Type second;
然后,您可以在avl_iterator
中定义:
value_type& operator * () const {
return _node->value;
}
value_type* operator -> () const {
return &_node->value;
}