在std::vector中搜索和计数特定元素的最快方法是什么?

C++ What would be the fastest way to search and count for a specific element within a std::vector?

本文关键字:元素 方法 是什么 vector std 搜索      更新时间:2023-10-16

如何在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_boundstd::upper_bound)。