Originally I had a member that was a std::vector<Point> with a method that did this:
bool Spline::Intersects(const Point& point) const {
return std::find(this->_result_points.begin(), _result_points.end(), point) != _result_points.end();
}
The design changed and std::vector<Point> became std::vector<Point*> and the previous method no longer worked and I had to change it to:
bool Spline::Intersects(const Point& point) const {
for(std::vector<Point*>::const_iterator _iter = _result_points.begin(); _iter != _result_points.end(); ++_iter) {
if(*(*_iter) == point) return true;
}
return false;
}
Does std::find perform the same linear search? If so, is there a faster/better/less gross way to do this (especially the double de-reference of the iterator)?
There are other places in the code that the std::find(this->_result_points.begin(), _result_points.end(), point) != _result_points.end(); (or similar, but opposite results) is performed and I would rather not have to use that slow linear for loop.
Yes,
finddoes the same linear search.You could hide the loop and the double indirection by using
find_ifwith a suitable predicate:bool operator()(Point* ptr) { return *ptr == point; }If you want to avoid linear searches, you need to change the way the data is stored. For example keeping the vector sorted would allow
std::binary_search, which is faster thanstd::find. That’s sorted by the value pointed to, not sorted by pointer value, so you’d need to pass a comparator tostd::sortetc. Or you could use an entirely different container: perhaps one of(unordered_)(multi)set.