在矢量中查找映射键的最快方法
Fastest method to find map keys in a vector
我正在寻找更快的方法来提取由矢量键过滤的地图值。
低于标准代码:
std::unordered_map<uint32, user> map;
std::vector<uint32> to_find;
std::vector<user> results;
auto it = map.begin();
while (it != map.end())
{
if (std::find(to_find.begin(), to_find.end(), it->first) == to_find.end())
results.push_back(it->second);
it++;
}
您可以使用std::binary_search((,它的时间复杂度为O(log n(,其中n
是向量to_find
的大小。这可能比使用具有线性时间复杂度的std::find()
要好得多。
演示
#include <algorithm>
#include <iostream>
#include <vector>
#include <unordered_map>
using user = int;
using uint32 = unsigned long int;
int main()
{
std::unordered_map<uint32, user> myMap = {{1,2},{3,5},{2,9},{4,7}};
std::vector<uint32> to_find = {1,3};
std::vector<user> results;
if(to_find.size() == 0) // if you have to_find vec size = 0
std::for_each(myMap.cbegin(), myMap.cend(), [&results](const auto& ele)->void
{
results.emplace_back(ele.second);
});
else
{
for(const auto& it: myMap)// binary_search; if not found add the value
if(!std::binary_search(to_find.begin(), to_find.end(), it.first))
results.emplace_back(it.second);
}
for(const auto& it: results) std::cout << it << std::endl;
}
如果两个容器都已排序,则线性方法是使用类似于std::merge
的算法:
template <typename KEY, typename VALUE>
std::vector<VALUE>
collect_absents(const std::map<KEY, VALUE>& map, const std::vector<KEY>& present)
{
std::vector<VALUE> res;
auto mit = map.begin();
auto vit = present.begin();
while (mit != map.end() && vit != present.end())
{
if (*vit < mit->first) {
++vit;
} else if (mit->first < *vit) {
res.push_back(mit->second);
++mit;
} else { // equal
++vit;
++mit;
}
}
for (; mit != map.end(); ++mit) {
res.push_back(mit->second);
}
return res;
}
演示
相关文章:
- 使用std::函数映射对象方法
- 在C++中初始化向量映射的最有效方法
- 拥有映射的现代方法,该映射可以指向或引用已在堆栈上分配的不同类型的数据
- C++ STD 函数运算符:有没有一种方法可以通过函数将一个向量映射到另一个向量上?
- 当映射包含字符串向量作为值时,从值中获取键的有效方法
- 映射唯一值和重复值的有效方法.可以访问键或值的位置
- 将一系列数字映射到 CPP 中的值的简单方法
- 使用迭代器替换映射中的常量项的方法
- C++-将对象(如字符串)映射到表中成员函数的正确方法
- 在矢量中查找映射键的最快方法
- 遍历 STL 映射(集/多集)的最佳方法,同时元素可能会在循环期间被删除并重新插入?
- C 正确的方法来初始化和处理映射指针
- 消息映射如何与 SendMessage() 方法交互?
- 检查是否存在多维映射的元素的最快方法是什么
- 在映射最小值和最大值时从未签名转换为已签名的最佳方法?
- 处理对存储在私有映射中的值的封装访问的标准方法,而不破坏C++中的抽象
- 使用静态映射在C++中缓存数据的推荐方法是什么
- C++通过映射并使用中的方法从基类实现派生类
- C++将一组整数变量映射到值的有效方法
- 在方法中构造一个std:映射一次