检查元素是否在两个向量中的最快方法
Fastest way to check if element is in both vectors
所以,认为我们有两个向量,vec1 和 vec2。仅对两个向量中的元素执行某些操作的最快方法是什么。到目前为止,我已经做到了。简单地说,我们如何才能更快地实现这一目标,或者有什么办法:
vector<Test*> vec1;
vector<Test*> vec2;
//Fill both of the vectors, with vec1 containing all existing
//objects of Test, and vec2 containing some of them.
for (Test* test : vec1){
//Check if test is in vec2
if (std::find(vec2.begin(), vec2.end(), test) != vec2.end){
//Do some stuff
}
}
你的方法是 O(M*N),因为它调用std::find
每个元素的 vec2
元素数量的线性vec1
。您可以通过多种方式对其进行改进:
-
排序
vec2
可以让您将时间减少到 O((N+M)*Log M) - 即您可以在范围上使用二叉搜索vec2.begin(), vec2.end()
- 对两个向量进行排序可以让您在 O(N LogN + M Log M中搜索) - 您可以使用类似于合并排序范围的算法来查找线性时间中的匹配对
-
对元素使用哈希集
vec2
可以让您将时间减少到 O(N+M) - 现在集合的构造时间和其中的搜索都是线性的。
一个简单的方法是std::unordered_set
vector<Test*> vec1;
vector<Test*> vec2;
//Fill both of the vectors, with vec1 containing all existing
//objects of Test, and vec2 containing some of them.
std::unordered_set<Test*> set2(vec2.begin(),vec2.end());
for (Test* t : vec1) {
//O(1) lookup in hash set
if (set2.find(t)!=set2.end()) {
//stuff
}
}
O(n+m),其中 n 是 vec1 中的元素数,m 是 vec2 中的元素数 }
相关文章:
- C++从另一个类访问公共静态向量的正确方法是什么
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 声明高维向量的更简洁的方法
- 在C++中初始化向量映射的最有效方法
- C++11 迭代向量的新方法?
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- C++:将向量传递到构造函数以创建成员变量的最佳方法?
- 有什么方法可以将具有不同模板参数的模板类实例放入向量中?
- 当映射包含字符串向量作为值时,从值中获取键的有效方法
- 在向量中查找大于 0(或通常为 k)的最小元素的最佳方法是什么?
- 从数组中删除非唯一值、保持顺序和不使用向量的最佳方法?
- 使用192/256位整数求和无符号64位整数向量的点积的最快方法
- 访问类成员向量最后一项的正确方法
- 使用 std::vector::swap 方法在C++中交换两个不同的向量是否安全?
- 从列表/向量制作嵌套 for 循环的最佳方法是什么?
- 检查两个向量是否并行的最有效方法
- 如何从 node-ffi 调用 c++ 中以结构向量作为参数的方法?
- 返回向量元素的 l 值的正确方法是什么?
- 如何在方法主体中返回声明向量的引用?