I am trying to implement a binary search tree container. At the moment I have to implement a find() function that is able to return an iterator or a constant iterator. I choose to overload the find function to accomodate both possibilities
MyIterator<treepair> find(const key& x)
{
return tree_search<MyIterator<treepair>>(root,x);
}
const_MyIterator<treepair> find(const key& x) const
{
return tree_search<const_MyIterator<treepair>>(root,x);
}
Then the function tree_search recursively finds the node that contains the wanted key by percurring the tree:
template<typename iterator>
iterator tree_search(Node<treepair>* x, const key& y) const
{
if(x == nullptr)
{
std::cout<<"element not found"<<std::endl;
iterator x = end();//HERE I HAVE A PROBLEM
return x;
}
else if (y == x->value.first)
{
iterator i{x,tree_maximum()};
std::cout<<"element found"<<std::endl;
return i;
}
if(y < x->value.first)
return tree_search<iterator>(x->left,y);
else return tree_search<iterator>(x->right,y);
}
Now the end() function is overloaded to give both a const_iterator and a regular iterator:
MyIterator<treepair> end(){
return MyIterator<treepair>{nullptr,tree_maximum()};
}
const_MyIterator<treepair> end() const{
return const_MyIterator<treepair>{nullptr,tree_maximum()};
}
however I receive this error
test_on_iterators.cc:508:12: error: conversion from ‘const_MyIterator<std::pair<int, int> >’ to non-scalar type ‘MyIterator<std::pair<int, int> >’ requested
iterator x = end();
Is this error due to a requirement in the conversion between the types? Isn't the compiler supposed to choose the wanted end() function according to the iterator type it has to produce?