Husky Husky - 1 month ago 10
C++ Question

How to use `copy_if` filter the `str` specific multiple of index

How to use

copy_if
filter the
str
specific multiple of index.

e.g.
str
is "1000020000300004000050000", I want the
newStr
is "12345".

According to 1 is 5*0, 2 is 5*1, 3 is 5*2, etc.




The source code :

std::string str("1000020000300004000050000");
std::string newStr;

std::copy_if(str.begin(), str.end(),
std::back_inserter(newStr),
[] (char c) {
// Some specific rule I want to return.
return ...;
}
);





The ideal code :

std::copy_if(str.begin(), str.end(),
std::back_inserter(newStr),
[] (char c) {
// I can get the index of iteration.
return (index % 5 == 0);
}
);

Answer

You can pass the string's begin and the current iterator as captures of the lambda function and use them accordingly (the lambda has to be mutable then):

std::string str("1000020000300004000050000");
std::string newStr;

std::copy_if(str.begin(), str.end(),
std::back_inserter(newStr),
[it = str.begin(), beg = str.begin()] (auto c) mutable {
    // I can get the index of iteration.
    return (std::distance(it++, beg) % 5 == 0);
}

DEMO

Comments