C++98下如何高效移除string vector中指定长度外的元素
Since C++98 doesn't support lambdas, we can use a custom functor (function object) to carry the target length variable—this plays nicely with the erase-remove idiom you already had in mind. Here's a straightforward, standards-compliant implementation:
Step 1: Define the Predicate Functor
We'll create a struct that holds the target length as a member variable, then overload the operator() to check if a string's length doesn't match the target. This lets us pass the dynamic user-provided length into the predicate.
#include <vector> #include <string> #include <algorithm> #include <iostream> // Functor to identify strings with mismatched lengths struct LengthMismatchChecker { int target_length; // Constructor to initialize with user's target length LengthMismatchChecker(int len) : target_length(len) {} // Overload operator() to perform the length check bool operator()(const std::string& str) const { return str.size() != target_length; } };
Step 2: Apply the Erase-Remove Idiom
Now you can use this functor with std::remove_if and vector::erase to efficiently filter your vector. The functor instance will carry the user's input value into the algorithm.
int main() { std::vector<std::string> str_vec = {"apple", "cat", "dog", "banana", "ant"}; int target_len; // Get user input for desired string length std::cout << "Enter target string length: "; std::cin >> target_len; // Remove elements that don't match the target length str_vec.erase( std::remove_if(str_vec.begin(), str_vec.end(), LengthMismatchChecker(target_len)), str_vec.end() ); // Print the filtered result std::cout << "Filtered vector:\n"; for (size_t i = 0; i < str_vec.size(); ++i) { std::cout << str_vec[i] << "\n"; } return 0; }
How This Works
- The functor
LengthMismatchCheckerstores the target length when it's constructed, so we can pass a dynamic value from user input directly into the predicate. std::remove_ifiterates through the vector, shifting all elements that match the predicate (i.e., length doesn't match the target) to the end of the vector.vector::erasethen trims those trailing elements, leaving only the strings with the correct length.
This approach maintains the O(n) time efficiency of the lambda-based version, while being fully compatible with C++98.
内容的提问来源于stack exchange,提问作者John Larkos

