我正在尋找向量元素到另一個向量中的位置。在這裏,我有興趣使用與binary search
一樣快的實現。我有不同的長度爲100萬或更多的矢量,所以我試圖更快地實現。在我的情況std :: vector中的二進制搜索
以下幾種情況:
1)vector
在我尋找排序。
2)元素我正在尋找將永遠存在即我沒有的not found
的情況下,我想獲得向量元素的索引以更快的方式。
我試過下面的代碼來獲取向量元素的索引。
#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;
}
我想知道如果代碼與二進制搜索實現匹配。??
有沒有更快的方法來獲得向量元素的索引?
有任何進一步的建議,以改善此代碼。
如果您發現自己在做這麼多關鍵性能的搜索,您可能需要考慮某種關聯容器。 – TartanLlama