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

::tolower using std::transform

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:

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::transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower);

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

>Solution :

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(c);
});
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