Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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;
}
like image 351
Jason Y Avatar asked Apr 27 '26 12:04

Jason Y


1 Answers

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());
like image 141
Enlico Avatar answered Apr 30 '26 00:04

Enlico