3

我想确保一个字符串至少有一个 alpha。简单的:

if ( find_if(field_name.begin(), field_name.end(), isalpha) == field_name.end() )

但我想使用一个locale. 我知道我可以轻松编写一个单独的函数,但我更喜欢在 find_if 中使用它。IE,

include <locale>

std::locale loc;

if ( find_if(field_name.begin(), field_name.end(), isalpha(*this_iterator,loc) == field_name.end() )

问题:有没有办法this_iterator引用当时的迭代器?

4

3 回答 3

7

在 C++11 中,您可以使用 Timo 建议的 lambda 或std::bind()使用std::bind(isalpha, std::placeholders::_1, loc).

Pre-C++11,你可以使用std::bind2nd()。不过这有点复杂,因为它需要一个unary_functionorbinary_function作为参数,而不是任何旧的函数对象。我们可以使用 来创建一个std::ptr_fun(),尽管出于某种原因我们需要明确地告诉它模板参数是什么。我们需要使用std::isalpha()而不是isalpha()为了获得启用语言环境的版本。所以完整的表达式看起来像

std::bind2nd(std::ptr_fun<char, const std::locale&, bool>(std::isalpha), loc)

不用说,C++11 版本要简单得多。


顺便说一句,如果您使用的是 C++11,那么您可以使用std::any_of(...)而不是std::find_if(...) == foo.end(). 它的行为应该相同,但更具可读性。

于 2012-12-13T00:32:25.267 回答
6

在 C++11 中,您可以使用 lambda:

if (std::find_if(field_name.begin(), field_name.end(),
                 [&loc](char c)
                 {
                   return isalpha(c, loc);
                 }) == field_name.end())
{
  ...
}

在 C++11 之前的版本中,您可能必须使用 boost::bind 或 boost::lambda 之类的东西来实现相同的功能。

于 2012-12-13T00:31:02.147 回答
3

在 C++11 之前的版本中,您可以isalpha()使用覆盖运算符的对象包装(),然后将其用作谓词,如果您不想使用std::bind...()或提升,例如:

#include <locale>

struct isalphaloc
{
    const std::locale &_loc;

    isalphaloc(const std::locale &loc) : _loc(loc) {}

    bool operator(const char c) const
    {
        return isalpha(c, _loc);
    }
};

.

std::locale loc;
if ( find_if(field_name.begin(), field_name.end(), isalphaloc(loc)) == field_name.end() )
于 2012-12-13T00:39:45.943 回答