在std::vector中搜索和计数特定元素的最快方法是什么?
C++ What would be the fastest way to search and count for a specific element within a std::vector?
如何在std::vector中搜索特定的元素并对其计数?它一定很快。请帮忙,谢谢。
这是我目前为止写的:
// Lets assume the Database is sorted (which it will be)
std::vector< std::string > Database( 3 );
Database.push_back( "Password123" );
Database.push_back( "HelloWorld!!!" );
Database.push_back( "HelloWorld!!!" );
//...
std::string Password = "HelloWorld!!!";
// Search and count Password?
// Should return true and 2
哦,我听说索引比迭代器慢。这是真的吗?
使用std::count
?
int num = std::count(Data.begin(), Data.end(), target);
但是如果这个"必须是快速的",那么你应该考虑在查询它之前对你的向量进行排序,因为这样你可以使用更快的方法来计数(例如std::lower_bound
和std::upper_bound
)。
相关文章:
- 数组元素打印的递归方法
- 如何实现 Front() 方法以返回模板化双向链表C++的第一个元素?
- 有什么方法可以将元素添加到列表中,如图所示?
- 在向量中查找大于 0(或通常为 k)的最小元素的最佳方法是什么?
- C++将所有元素从矢量复制到地图/unordered_map的最佳方法
- 在C++中更改结构内部元素的方法?
- 通过作为指向 C++ 函数的指针传递来访问 std::array 元素的正确方法是什么?
- 有没有更快的方法可以在 std::vector 中插入元素
- 返回向量元素的 l 值的正确方法是什么?
- 按升序打印矢量的所有元素直到它为空而没有重复项的最有效方法是什么?
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- 如何在不迭代的情况下对数组中的每个元素调用方法
- 是否有更有效的方法来检查元素是否在给定的区间内
- 这种获取模板参数包中最后一个元素的方法是否有隐藏的开销?
- 将__m256的奇怪元素提取到__m128中的有效(在锐龙上)方法?
- 为什么 memcpy() 是一种将元素添加到 'std::map' 的方法?
- 从长(且合理)稀疏向量中选择随机元素的最有效方法是什么?
- 如何使用返回第 n 个元素的方法创建元组
- 带有移除任何元素方法的c++堆
- 如何在带有input的map元素方法上使用std::for_each