问题描述
我有这样的东西:
class Bar
{
public:
pair<string,string> one;
std::vector<string> cars;
Bar(string one, string two, string car);
};
class Car
{
public:
string rz;
Bar* owner;
Car(string car, Bar* p);
};
class Foo
{
public:
Foo ( void );
~Foo ( void );
int Count ( const string & one, const string & two) const;
int comparator (const Bar & first, const Bar & second) const;
std::vector<Bar> bars;
};
int Foo::comparator(const Bar & first, const Bar & second) const{
return first.name < second.name;
}
int Foo::Count ( const string & one, const string & two ) const{
int result=0;
Bar mybar = Bar( one, two, "" );
std::vector<Bar>::iterator ToFind = lower_bound(bars.begin(), bars.end(), mybar, comparator);
if (ToFind != bars.end() && ToFind->one == mybar.one ){
result = ...
}
return result;
}
方法 Foo :: Count
应该使用 std :: lower_bound()
在 vector< Bar>
字符串。
现在不起作用的部分。至 lower_bound()
我提供了方法 comparator()
。我认为它没问题,但g ++说:
The method Foo::Count
should use std::lower_bound()
to find element in vector<Bar>
according to pair of two strings.Now the part which doesn't work. To lower_bound()
I'm providing method comparator()
. I thought it was okay, but g++ says:
c.cpp: In member function ‘int Foo::Count(const string&, const string&) const’:
c.cpp:42:94: error: invalid use of non-static member function
std::vector<Bar>::iterator ToFind = lower_bound(bars.begin(), bars.end(), mybar, comparator);
方法 Count()
必须停留 const
...
And the method Count()
must stay const
...
我对C ++很陌生,因为我不得不学习它。
I'm quite new to C++ because I'm forced to learn it.
有什么想法?
Any ideas?
推荐答案
c> Foo :: comparator static或将其包装在 std :: mem_fun
类对象中。这是因为lower_bounds期望比较器是一个具有调用操作符的对象类,如函数指针或函子对象。另外,如果您使用的是C ++ 11或更高版本,那么您也可以像所建议的那样使用lambda函数。 C ++ 11也有 std :: bind
。
You must make Foo::comparator
static or wrap it in a std::mem_fun
class object. This is because lower_bounds expects the comparor to be a class of object that has a call operator, like a function pointer or a functor object. Also, if you are using C++11 or later, you can also do as dwcanillas suggests and use a lambda function. C++11 also has std::bind
too.
示例:
// Binding:
std::lower_bounds(first, last, value, std::bind(&Foo::comparitor, this, _1, _2));
// Lambda:
std::lower_bounds(first, last, value, [](const Bar & first, const Bar & second) { return ...; });
这篇关于无效使用非静态成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!