I am trying to look for the position of vector elements into another vector. Here i am interested to use an implementation as fast as binary search
. I have different vectors of length 1 million or more, so i am trying to achieve something faster.
Following situations in my case:
1) vector
in which i am searching is sorted.
2) The element i am searching for will always be there i.e i don't have a case of not found
, and i would like to get the index of vector elements in a faster way.
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 code matches with the binary search implementation.??
Is there a faster way to get the index of vector elements?
Any further suggestions to improve this code.