user2117427
user2117427

Reputation: 487

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

How do we search for a specific element and count it within a std::vector? It MUST be fast. Please help, thank you.

This is what I have so far:

// 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

Oh and I heard indexing is slower than iterator. Is it true?

Upvotes: 0

Views: 791

Answers (1)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272657

Use std::count?

int num = std::count(Data.begin(), Data.end(), target);

But if this "MUST be fast", then you should consider sorting your vector before querying it, because then you can use faster approaches to counting (e.g. std::lower_bound and std::upper_bound).

Upvotes: 5

Related Questions