2
我有一個自定義容器來存儲數據和一個迭代器來訪問它。問題是迭代器中的 - >運算符不允許我修改容器中的數據。問題重載arrow( - >)operator C++
VALUE_TYPE是一個std ::對<>
數據保持器:
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";
}
能告訴你的客戶端代碼? – 2013-02-23 22:11:03
@AndyProwl,如果你的意思是用來測試的代碼,它被加到帖子底部 – 2013-02-23 22:15:09
是的,這就是我的意思 – 2013-02-23 22:15:45