I wrote a little (working) test code but I do not understand why in the test1 function I can only pass a int* const as parameter while in the test2 function I can pass a const int*. If I pass a const int* to test1, I get a discard qualifier error.
In my research, I found that both std::find and set::find have a const version so I can't see why they behave differently. I also tried with boost::container::flat_set instead of a std::set and I got the same result.
Could someone explain me please?
class myClass
{
public:
myClass() {};
~myClass() {};
void add(int* ref)
{
this->_ref.insert(ref);
};
bool test1(int* const ref) const
{
return ( this->_ref.find(ref) != this->_ref.end() );
}
inline
bool test2(const int* ref) const
{
return ( std::find(this->_ref.begin(), this->_ref.end(), ref) != this->_ref.end() );
}
std::set<int*> _ref;
};
int main()
{
myClass test;
test.add(new int(18));
test.add(new int(35));
test.add(new int(78));
test.add(new int(156));
std::cout<<test.test1(0)<<std::endl;
std::cout<<test.test1(*test._ref.begin())<<std::endl;
std::cout<<test.test2(0)<<std::endl;
std::cout<<test.test2(*test._ref.begin())<<std::endl;
return 0;
}
set::find() gives the answer in O(logN) while std::find() gives the answer in O(N) .
Similarly, map::find() gives the answer in O(logN) while std::find() gives the answer in O(N) .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With