简体   繁体   中英

Copy a std::string using copy_if (into another string)

I'm wondering what's the best way to selectively copy_if characters from one string to another. I have something like

string buffer1("SomeUnknownwSizeAtCompileTime");
string buffer2; // WillBeAtMostSameSizeAsBuffer1ButMaybeLessAfterWeRemoveSpaces
buffer2.resize(buffer1.length());
std::copy_if(buffer1.begin(), buffer1.end(), buffer2.begin(), [](char c){
            //don't copy spaces
            return c != ' ';
});

buffer2 could potentially be a lot smaller than buffer1, yet we have to allocate the same amount of memory as buffer1's length. After copying however, buffer2's end iterator will point past the null termination character. I googled around and apparently this is by design, so now I'm wondering should I not be using copy_if with strings?

Thanks

You need to use std::back_inserter .

#include <iterator>

std::copy_if(buffer1.begin(), buffer1.end(), back_inserter(buffer2), [](char c){
        //don't copy spaces
        return c != ' ';
});

back_inserter(buffer2) returns a specialized iterator which appends to instead of overwriting the elements of buffer2 .

For this to work correctly, you'll have to make sure that you start out with an empty buffer2 . ie don't use:

 buffer2.resize(buffer1.length());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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