在 C++ 中使用 "transform" 会给出一个错误,指出这未在作用域中声明

using "transform" in c++ gives an error that this was not declared in the scope

本文关键字:错误 一个 声明 作用域 C++ transform      更新时间:2023-10-16

我正在使用 transform 将字符串转换为小写,编译器给出一个错误,指出 transform 未在范围内声明。

transform(my_str.begin(), my_str.end(), my_str.begin(), ::tolower);

或者告诉我解决此问题的替代解决方案,谢谢!

根据transform的文档,这是std命名空间中的一个函数。您必须包含正确的头文件,并限定函数名称:

#include <algorithm>
std::transform(my_str.begin(), my_str.end(), my_str.begin(), ::tolower);

如果你不能使用transform::tolower,那么你必须假设 ASCII 编码, 实现自己的降低,然后使用for循环转换string

#include    <iostream>
#include    <string>
char mytolower (char c) {
constexpr int shift = 'A' - 'a';
if (c >= 'A' && c <= 'Z') {
c -= shift;
}
return c;
}
int main () {
std::string s = "sAcVZu";
for (char &c: s) {
c = mytolower (c);
}
std::cout << s;
}
相关文章: