So far, I have been storing the array in a vector and then looping through the vector to find the matching element and then returning the index.
Is there a faster way to do this in C++? The STL structure I use to store the array doesn’t really matter to me (it doesn’t have to be a vector). My array is also unique (no repeating elements) and ordered (e.g. a list of dates going forward in time).
Since the elements are sorted, you can use a binary search to find the matching element. The C++ Standard Library has a
std::lower_boundalgorithm that can be used for this purpose. I would recommend wrapping it in your own binary search algorithm, for clarity and simplicity:(The C++ Standard Library has a
std::binary_search, but it returns abool:trueif the range contains the element,falseotherwise. It’s not useful if you want an iterator to the element.)Once you have an iterator to the element, you can use
std::distancealgorithm to compute the index of the element in the range.Both of these algorithms work equally well any random access sequence, including both
std::vectorand ordinary arrays.