Refactor Legacy C++ Code to Enhance Readability and Performance
Given a legacy C++ function that processes and filters a vector of user data with multiple nested loops and repeated conditions, refactor the code to improve readability, reduce complexity, and optimize performance while preserving the original behavior.
Challenge prompt
You are provided with a legacy C++ function that takes a vector of users (with name, age, and score) and returns a filtered vector based on complex criteria. The original code contains nested loops, repeated conditions, and unnecessary copies. Refactor the function to improve code clarity, reduce complexity, and enhance performance without changing the output. Keep the function signature the same. Write clean, modern C++ code using best practices.
Guidance
- • Analyze the current nested loops and condition checks to identify redundancies.
- • Use STL algorithms and standard library features to simplify code.
- • Avoid unnecessary copying of objects by using references and move semantics where appropriate.
- • Ensure the refactored function returns the exact same filtered results as the original.
Hints
- • Consider using std::copy_if or std::remove_if combined with lambda expressions to simplify filtering.
- • Use structured bindings and const references for better readability and efficiency.
- • Break down complex conditions into well-named boolean variables or helper functions.
Starter code
#include <vector>
#include <string>
struct User {
std::string name;
int age;
double score;
};
std::vector<User> filterUsers(const std::vector<User>& users) {
std::vector<User> result;
for (size_t i = 0; i < users.size(); ++i) {
if (users[i].age > 18) {
for (size_t j = 0; j < users.size(); ++j) {
if (j != i) {
if (users[j].score > 50.0) {
if (users[i].score > 70.0) {
result.push_back(users[i]);
break;
}
}
}
}
}
}
return result;
}
Expected output
The refactored function returns a vector of Users from the input where the user's age is greater than 18, the user has score above 70, and there exists at least one other user with score above 50. The output matches exactly what the original function would produce but with cleaner, more efficient code.
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.