gpt4 book ai didi

c++ -::运算符必须与 tolower() 一起使用吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:57:17 30 4
gpt4 key购买 nike

transform(mystr.begin(), mystr.end(), mystr.begin(), tolower);

我正在使用 transform 函数使字符串全部为小写字母,但即使在编写“using namespace std;”之后也是如此在我的程序的顶部,我得到了一大堆错误(当像上面那样写的时候)。当我在 tolower 参数之前包含::运算符时(如下所示),我不这样做。为什么是这样?我认为 tolower 函数在 std 命名空间中,它会像上面那样工作。

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

我有以下内容:

#include <iostream>
#include <fstream
#include <sstream>
#include <algorithm>
#include <vector>

在我看到的错误信息中:

error: no matching function for call to 'transform(std::basic_string<char>::iterator, ...

然后是'tolower'在参数列表中的位置

, <unresolved overloaded function type>);'

最佳答案

嗯,这有点复杂。添加#include <cctype>可能会解决您的问题。然而,还有更多事情正在发生。

tolower有这两个版本:

int std::tolower(int ch);                           // #include <cctype>

template<typename charT>
charT std::tolower(charT ch, const std::locale& loc); // #include <locale>

但也可能有这个版本:

int ::tolower(int ch);    // #include <cctype> or #include <ctype.h>

因为允许实现从 std 注入(inject)名称进入全局命名空间。另外,你不能指望 cctypelocale被包含或不被包含,因为任何标准包含也可能包含任何其他标准包含。


您似乎打算使用 <cctype> 中的版本.但是,那将是一个错误。如果您查看该版本 tolower 的文档你会看到参数应该转换为unsigned char 在传递给函数之前。

IOW,通过 chartolower 的 cctype 版本具有负值导致未定义的行为。 (虽然常见的实现支持它,因为它是一个常见的错误)。

要更正您的代码并仍然使用 cctype 版本,您可以这样写:

#include <cctype>

// ...

transform(mystr.begin(), mystr.end(), mystr.begin(),
[](char ch) { return std::tolower( (unsigned char)ch ); } );

虽然看起来用起来简单了点:

for (char &ch : mystr)
ch = std::tolower( (unsigned char)ch );

<locale>版本看起来像(记住它是一个函数模板):

#include <locale>
#include <functional>

// ...

transform(mystr.begin(), mystr.end(), mystr.begin(),
std::bind( std::tolower<char>, std::placeholders::_1, std::locale() ) );

std::locale loc;

for ( char &ch : mystr )
ch = std::tolower(ch, loc);

关于c++ -::运算符必须与 tolower() 一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30818214/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com