使用仿函数调用find_if的编译错误

Jim*_*ong 3 c++ stl

我们在使用find_if搜索对的向量时遇到一些麻烦,对于该对象的第一个元素匹配特定值.为了完成这项工作,我们定义了一个简单的函子,其operator()将一对作为输入,并将第一个条目与字符串进行比较.

不幸的是,当我们实际使用使用临时字符串值构造的函数实例添加对find_if的调用时,编译器会生成大量错误消息.奇怪(对我来说,无论如何),如果我们用我们在堆栈上创建的字符串替换临时字符,事情似乎有效.

这是代码(包括两个版本)的样子:

typedef std::pair<std::string, std::string> MyPair;
typedef std::vector<MyPair> MyVector;

struct MyFunctor: std::unary_function <const MyPair&, bool>
{
  explicit MyFunctor(const std::string& val)
    : m_val(val) {}

  bool operator() (const MyPair& p)
  {
    return p.first == m_val;
  }

  const std::string m_val;
};

bool f(const char* s)
{
  MyFunctor f(std::string(s));  // ERROR
  // std::string str(s);                                                                                                  
  // MyFunctor f(str);              // OK                                                                                                    
  MyVector vec;
  MyVector::const_iterator i = std::find_if(vec.begin(), vec.end(), f);
  return i != vec.end();
}
Run Code Online (Sandbox Code Playgroud)

这是最有趣的错误消息:

/usr/include/c++/4.2.1/bits/stl_algo.h:260:错误:从'std :: pair,std :: allocator>,std :: basic_string,std :: allocator >>'转换为非请求标量类型'std :: string'

因为我们有一个解决方法,所以我们对第一种形式导致问题的原因感到好奇.我确定我们错过了什么,但我们无法弄清楚它是什么.

Mat*_*hen 6

这是最令人烦恼的解析.

你可以做:

MyFunctor f(s);
Run Code Online (Sandbox Code Playgroud)

要么

MyFunctor f((std::string(s)));
Run Code Online (Sandbox Code Playgroud)

原始声明一个函数f. f采用一个参数,一个指向函数的指针,该函数接受一个参数s并返回std::string.