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;
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;
}
You haven't allocated any space in result, so you are observing a pretty "gentle" case of undefined behavior ("gentle" because the program is observably not working, rather than happening to work by pure luck).
To solve the problem, you can either allocate such memory before calling std::transform, e.g. via
result.resize(inputString.size());
or 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, it is still probably a good idea to reserve some space via
result.reserve/* not resize! */(inputString.size());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With