template<typename TIterator> // 需要random iterator,如果使用了C++ concept的话可以有效美化错误信息
bool find(TIterator begin, TIterator end, std::remove_reference_t<decltype(**(TIterator*)nullptr)> value)
{
auto size = end - begin;
if (size <= 0) return false;
auto position = begin + (size / 2);
auto middle = *position;
if (middle > value) return findx(begin, position, value);
if (middle < value) return findx(position+1, end, value);
return true;
}
vector<int> x = {1, 2, 3, 4, 5};
find(x.begin(), x.end(), 2); // true
find(x.begin() + 2, x.begin() + 3, 2); // false
It can be seen that iterator was invented to simulate the concept of pointer. However, pointer arithmetic requires that the content is stored continuously, while iterator does not. So for the convenience of thinking, you only need to think of iterator as a pointer.
You can write: vec.begin() + i; or vec[i]
In addition, when using vector, it is better to pass "reference".
void func(vector<int>& vec);
STL uses iterator to abstract. In your case, regardless of whether func is read-only, you can refer to the writing method of std::sort.
In general, that’s it,
changed to
As a simple example, binary search method:
It can be seen that iterator was invented to simulate the concept of pointer. However, pointer arithmetic requires that the content is stored continuously, while iterator does not. So for the convenience of thinking, you only need to think of iterator as a pointer.