我试图了解如何使用std::tolower ...
I try to understand how to use std::tolower...
#include <iostream> #include <string> #include <algorithm> #include <locale> int main() { std::string test = "Hello World"; std::locale loc; for (auto &c : test) { c = std::tolower(c, loc); } std::transform(test.begin(), test.end(), test.begin(), ::tolower); // 1) OK std::transform(test.begin(), test.end(), test.begin(), std::tolower); // 2) Cryptic compile error std::transform(test.begin(), test.end(), test.begin(), static_cast<int(*)(int)>(std::tolower)); // 3) Cryptic compile error. Seems OK with other compilers though return 0; }所以:
推荐答案
首先,请注意,这些方法中的没有都以可移植的方式完成了正确的工作!问题是char可能是带符号的(通常是带符号的),但是tolower()的版本仅接受正值!那就是您真的想使用std::tolower()这样的东西:
First off, note, that none of these approaches does the right thing in a portable way! The problem is that char may be signed (and typically is) but the versions of tolower() only accept positive values! That is you really want to use std::tolower() using something like this:
std::transform(test.begin(), test.end(), test.begin(), [](unsigned char c) { return std::tolower(c); });(或者,如果您对C ++ 03感到困惑,当然可以使用相应的函数对象).将std::tolower()(或::tolower())用作负值会导致未定义的行为.当然,这仅在签署了char的平台上才有意义,但是,这似乎是典型的选择.
(or, of course, using a corresponding function object if you are stuck with C++03). Using std::tolower() (or ::tolower() for that matter) with a negative value results in undefined behavior. Of course, this only matters on platform where char is signed which seems, however, to be the typical choice.
要回答您的问题:
值得注意的是,使用函数对象而不是函数指针通常要快很多,因为内联函数对象并不容易,而内联函数指针却不那么容易.在实际上知道函数的地方使用内联函数指针,编译器会变得更好,但是当代的编译器当然并不总是通过函数指针内联函数调用,即使所有上下文都在那里.
It is worth noting that using a function object rather than a function pointer is typically a lot faster because it is trivial to inline the function object but not as trivial to inline the function pointer. Compilers are getting better with inlining the use of function pointers where the function is actually known but contemporary compilers certainly don't always inline function calls through function pointers even if all the context would be there.
更多推荐
std :: tolower和Visual Studio 2013
发布评论