在使用二元谓词的find_first_of函数上给出错误
gives error on find_first_of function with binary predicate
代码
#include <string>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class test {
struct con {
string s1;
string s2;
};
public:
void somefunc();
private:
bool pred(con c1, con c2);
vector<con> vec;
};
void test::somefunc()
{
vector<con> v;
vector<con>::iterator it = find_first_of(vec.begin(), vec.end(), v.begin(), v.end(), pred);
}
bool test::pred(con c1, con c2)
{
return 0;
}
给出错误
est.cpp(24):错误C2664: 'struct test::con *__cdecl std::find_first_of(struct test::con *,struct test::con *,struct test::con *,struct test::con *,struct test::con *,struct test::con *,struct test::con *,bool (__thiscall *)(struct test::con不能将参数5从bool (struct test::con,struct test::con)'转换为bool (__thiscall *)(struct test::con,struct test::con)'作用域中没有一个具有此名称的函数匹配目标类型
我不明白什么是(__thiscall*)以及如何将我的谓词函数转换为它
谓词不能是非静态成员函数,因为它接受隐式的第一个参数,总共给出三个参数。您要么需要静态成员函数,要么需要非成员函数:
// non-member function
bool pred(const con& c1, const con& c2)
{
return false;
}
void test::somefunc()
{
vector<con> v;
vector<con>::iterator it = find_first_of(vec.begin(), vec.end(),
v.begin(), v.end(),
pred);
}
或者,使用std::bind
绑定this
作为第一个参数:
using namespace std::placeholders;
vector<con>::iterator it = find_first_of(vec.begin(), vec.end(),
v.begin(), v.end(),
std::bind(&test::pred, this, _1, _2));
对std::bind
的调用产生一个具有两个con
参数的可调用实体。它在内部存储this
指针的副本(但this
不用于pred
函数)。
__thiscall
是仅msvc++用于非静态成员函数的调用约定。
在您的代码中,pred
是一个非静态成员函数,如果没有std::bind
之类的解决方案,它不能用作二进制谓词。我建议你把这个函数设为static
。或者更好地使用lambda(仅限c++ 11)。
谓词是一个非静态成员函数。要么将其设为静态(或简单地设为非成员函数),要么使用std::bind()
(或等效的Boost)。如果你负担不起c++ 11)绑定:
#include <functional>
// ...
vector<con>::iterator it = find_first_of(
vec.begin(), vec.end(), v.begin(), v.end(),
std::bind(&test::pred, this, std::placeholders::_1, std::placeholders::_2));
下面是一个的实例。
如果您选择将函数保留为成员函数并使用std::bind()
,请考虑将函数pred()
限定为const
,因为不应该改变调用它的对象的状态。
- Usages of std::move
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- 具有变量Number of Arguments的std::函数的矢量
- Capacity of a deque
- Deprecation of _writeBarrier()
- constexpr begin of a std::array
- 如何调整 std::vector of Eigen::MatrixXd 的大小
- C++ "error: invalid use of void expression"
- 我看到"use of undeclared identifier"错误,有人可以告诉我如何解决它吗?
- C++算法标头中,为什么要使用 "!(val < *first)" ?
- 赛通"Cannot take address of memoryview slice"
- C++ Version Of Double.longBitsToDouble
- 收到错误"invalid use of non-static data member 'stu::n' "
- C++ Usage of AsyncCallback
- 错误:"Left of getValue must have class/struct/union"
- Centos7 g++ "to_string is not in a member of std"
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- C++ 字符串迭代器"find first of"
- "Multiple definition of.." "First defined here"数据结构中的同一行中