1

Suppose I am given an string vector vector<string> names = {"ab","abs","act","add"}. I am also given a string prefix string prefix ("ab"). My job is to populate another string vector (let's call it vector<string> name_list) with all the names that begin with the given prefix. Currently I am doing this by simply using a string compare function like follows:

for (int i = 0; i < names.size(); ++i)
{
    if (names[i].compare(0, prefix.size(), prefix) == 0) // If name begins with prefix
        (*name_list).push_back(names[i]);
}

This works well for small vectors. In the example above the output would be ["ab","abs"] My question is if this is the most efficient algorithm when the names has let's say millions of strings in it. If not, what other algorithms could be used?

2
  • 1
    To save some memory you could read the strings into a trie Commented Feb 27, 2014 at 1:19
  • I think using a suffix array can reduce the number of comparison. Commented Feb 27, 2014 at 1:19

1 Answer 1

1

Start from the iterator retrned by std::set<std::string>::lower_bound(prefix) and search linearly forward.

std::set<std::string> names {"ab","abs","act","add"};
std::string prefix = "ab";
auto itr = names.lower_bound(prefix);
while (itr != names.end() && !prefix.compare(*itr, 0, prefix.size())) {
     // matching string
     ++itr;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.