我们如何搜索特定元素并在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)。

10-07 19:25
查看更多