You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++98下如何高效移除string vector中指定长度外的元素

Solution for C++98: Remove Vector Elements with Mismatched Lengths

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 LengthMismatchChecker stores the target length when it's constructed, so we can pass a dynamic value from user input directly into the predicate.
  • std::remove_if iterates 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::erase then 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:08:47