Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why does my std::transform retuns nothing/empty string?

can you help explain me how to use std::transform ?
I need to create a function that returns a string and has a string as parameter
and use std::transform to convert all the uppercase char to lower and vice versa lowercase char to uppercase
example:
input = "aBc"
output = "AbC"

and i want to do it with a lambda, not using other mehtod like toupper, etc.

​​​​​​this is what i have so far which doesnt work, it compiles and runs but it returns nothing/ empty string;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

std::string func(std::string inputString){
        std::string result;
        std::transform(inputString.begin(), inputString.end(), result.begin(), [](char& c){
                if (c < 97) return c + 32;
                if (c >= 97) return c - 32;
        });
        return result;
}

>Solution :

You haven’t allocated any space in result, so you are observing a pretty gentle case of undefined behavior (gentle because it’s observably not working, rather than happening to work by pure luck).

So you either allocate such memory before calling std::transform, e.g. via

result.resize(inputString.size());

or you can use a back_inserter for result, instead of its begin iterator result.begin(), which will take care of the allocation; the page on std::transform has such an example. In this latter case, is still probably a good idea to reserve some space via

result.reserve/* not resize! */(inputString.size());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading