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:
std::vector<std::string>
.std::string::starts_with()
to find matches (C++20 feature).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:
prefix
and a dictionary
as input.suggestions
to store matching words.starts_with()
), it's added to 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:
std::sort()
.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.
Answers to questions are automatically generated and may not have been reviewed.
std::string
ClassA detailed guide to std::string
, covering the most essential methods and operators