简体   繁体   English

如何有效地从一定长度的字符串向量中删除单词

[英]How to efficiently remove words from a string vector of certain length

I am currently trying to work with a vector of strings, and need to be able to efficiently remove elements that are not of a certain string length. 我目前正在尝试使用向量字符串,并且需要能够有效地删除不是特定字符串长度的元素。

I was thinking about doing something like vector.erase(remove_if(etc)) , however I can't use lambdas due to using C++98, and if I were to create a predicate it would need parameters because the length is a variable and can change based on user input. 我当时正在考虑做诸如vector.erase(remove_if(etc))类的vector.erase(remove_if(etc)) ,但是由于使用了C ++ 98,所以我不能使用lambdas,并且如果我要创建一个谓词,那么它将需要参数,因为长度是一个变量并且可以根据用户输入进行更改。

Can anyone provide a basic solution to this with these restrictions? 在这些限制下,谁能提供对此的基本解决方案?

It's not like in C++03 you didn't have functors, they were just 10x more awkward to use... 这与在C ++ 03中没有函子不同,使用函子只是笨拙的十倍...

// important: outside from any function
// (local types weren't allowed as template parameters) 
struct size_mismatcher {
    size_t size;
    size_mismatcher(size_t size) : size(size) {}
    bool operator()(const std::string& s) { return s.size() != size; }
};

// in your function:
vec.erase(std::remove_if(vec.begin(), vec.end(),
                         size_mismatcher(target_size)),
          vec.end());

Or just do it the classic way: 或者只是以经典的方式来做:

size_t wp = 0;
for(size_t rp = 0, n = vec.size(); rp != n; ++rp) {
    if(vec[rp].size() == target_size) {
        vec[wp] = vec[rp];
        ++wp;
    }
}
vec.resize(wp);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM