Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

::tolower using std::transform [duplicate]

Why std::transform doesn't work this way:

std::string tmp = "WELCOME";
std::string out = "";
std::transform(tmp.begin(), tmp.end(), out.begin(), ::tolower);

out is empty!

But this works:

std::transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower);

I don't want the transformation to happen in-place.

like image 914
Xigma Avatar asked Jul 23 '26 22:07

Xigma


1 Answers

You are writing in out-of-bounds memory, since the range of out is smaller than that of tmp. You can store the result in out by applying std::back_inserter.

As user17732522 pointed out, since it's not legal to take the adress of a standard libary function, it's better to pass over a lamda object that calls std::tolower on the character when needed.

std::transform(tmp.begin(), tmp.end(), std::back_inserter(out), [](auto c) {
    return std::tolower(static_cast<unsigned char>(c));
});
like image 143
Stack Danny Avatar answered Jul 27 '26 16:07

Stack Danny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!