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

Jas*_*n Y 2 c++

can you help explain me how to use std::transform ?\nI need to create a function that returns a string and has a string as parameter\nand use std::transform to convert all the uppercase char to lower and vice versa lowercase char to uppercase\nexample:\ninput = "aBc"\noutput = "AbC"

\n

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

\n

\xe2\x80\x8b\xe2\x80\x8b\xe2\x80\x8b\xe2\x80\x8b\xe2\x80\x8b\xe2\x80\x8bthis is what i have so far which doesnt work, it compiles and runs but it returns nothing/ empty string;

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

Enr*_*lis 7

您尚未在 中分配任何空间result,因此您正在观察未定义行为的相当“温和”的情况(“温和”是因为程序明显无法工作,而不是纯粹靠运气工作)。

要解决这个问题,您可以在调用之前分配这样的内存std::transform,例如通过

result.resize(inputString.size());
Run Code Online (Sandbox Code Playgroud)

或者使用back_inserterfor result(而不是它的 begin 迭代器result.begin()),它将负责分配;的页面std::transform有这样的例子。在后一种情况下,通过以下方式保留一些空间可能仍然是一个好主意

result.reserve/* not resize! */(inputString.size());
Run Code Online (Sandbox Code Playgroud)