I am trying to find the position of vector elements in another vector. Here, I am interested in using an implementation as fast as binary search . I have different vectors of 1 million or more in length, so I'm trying to achieve something faster.
The following situations are in my case:
1) vector in which I am looking is sorted.
2) The element I'm looking for will always be there, i.e. I have no case of not found , and I would like to get the index of vector elements faster,
I tried the following code to get the index of vector elements.
#include <iostream> #include <vector> #include <algorithm> template<class Iter, class T> Iter binary_find(Iter begin, Iter end, T val) { Iter i = std::lower_bound(begin, end, val); return i; } int main() { std::vector<std::string> values = {"AAAAAA","AB", "AD" ,"BCD","CD", "DD" }; std::vector<std::string> tests = {"AB", "CD","AD", "DD"}; for(int i=0 ; i < tests.size(); i++) { int pos = binary_find(values.begin(), values.end(), tests.at(i))- values.begin(); std::cout << tests.at(i) << " found at: " << pos <<std::endl; } return 0; }
I would like to know if the binary search implementation code matches.
Is there a faster way to get the index of vector elements?
Other suggestions for improving this code.