0

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

1 Answer 1

7

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. i.e. don't use:

 buffer2.resize(buffer1.length());
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your comment. I dismissed looking around back_inserters alltogther because I thought that required an actual method called push_back. Guess it can change container to container. Anyway, with regards to performance, I presume I'm at the mercy of the std::string's growth. If I expect a rough size for the string can I do anything to prevent the number or new allocations as I back insert into the new string?
String has a method called push_back, back_inserter wouldn't work otherwise. String also has a reserve method similar to vector, if you call that with your approximate size it will prevent reallocations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.