Implementing Basic Autocomplete
How can I implement a basic autocomplete feature using a list of std::string
s?
Implementing a basic autocomplete feature using std::string
is a great way to practice string manipulation and searching. Let's create a simple autocomplete function that suggests words from a predefined list based on a user's input prefix.
Here's a step-by-step implementation:
- Create a list of words (our dictionary) using
std::vector<std::string>
. - Write a function that takes a prefix and the dictionary as input.
- Use
std::string::starts_with()
to find matches (C++20 feature). - Return a list of matching words.
Here's the code implementation:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
std::vector<std::string> autocomplete(
const std::string& prefix,
const std::vector<std::string>& dictionary) {
std::vector<std::string> suggestions;
for (const auto& word : dictionary) {
if (word.starts_with(prefix)) {
suggestions.push_back(word);
}
}
return suggestions;
}
int main() {
std::vector<std::string> dictionary{
"cat", "dog", "elephant",
"lion", "tiger", "leopard"
};
std::string prefix;
std::cout << "Enter a prefix: ";
std::cin >> prefix;
auto suggestions =
autocomplete(prefix, dictionary);
std::cout << "Suggestions:\n";
for (const auto& suggestion : suggestions) {
std::cout << suggestion << '\n';
}
}
Enter a prefix: l
Suggestions:
lion
leopard
Let's break down the autocomplete()
function:
- It takes a
prefix
and adictionary
as input. - It creates an empty vector
suggestions
to store matching words. - It iterates through each word in the dictionary.
- If a word starts with the given prefix (using
starts_with()
), it's added tosuggestions
. - Finally, it returns the list of suggestions.
In main()
, we create a sample dictionary, get a prefix from the user, call autocomplete()
, and print the suggestions.
This basic implementation can be enhanced in several ways:
- Sort the suggestions alphabetically using
std::sort()
. - Limit the number of suggestions returned.
- Implement case-insensitive matching.
- Use more efficient data structures like tries for larger dictionaries.
Remember, std::string::starts_with()
is a C++20 feature. If you're using an older C++ version, you can replace it with:
if (word.substr(0, prefix.length()) == prefix) {
suggestions.push_back(word);
}
This autocomplete feature demonstrates the power and flexibility of std::string
in C++, showcasing methods like starts_with()
and how they can be used in practical applications.
A Deeper Look at the std::string
Class
A detailed guide to std::string
, covering the most essential methods and operators