我正在尝试将以下 class Table
中的函数 filterX()
和 filterY()
概括为函数 filter( )
。
函数 filterX()
和 filterY()
的区别仅在于它们在过程中调用的函数。当 filterX()
调用 getX()
时,filterY()
调用 getY()
。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Row
{
public:
void add(string x, string y, int val);
string getX() const { return d_x; }
string getY() const { return d_y; }
int getVal() const { return d_val; }
private:
string d_x;
string d_y;
int d_val;
};
class Table
{
public:
void add(string x, string y, int val);
vector<int> filterX(string s);
vector<int> filterY(string s);
private:
vector<Row> d_table;
};
//--------------------class Row----------------------------
void Row::add(string x, string y, int val)
{
d_x = x;
d_y = y;
d_val = val;
}
//-------------------class Table---------------------------
void Table::add(string x, string y, int val)
{
Row r;
r.add(x, y, val);
d_table.push_back(r);
}
vector<int> Table::filterX(string s)
{
vector<int> result;
vector<Row>::iterator it;
for(it = d_table.begin(); it != d_table.end(); ++it) {
if(it->getX() == s) {
int val = it->getVal();
result.push_back(val);
}
}
return result;
}
vector<int> Table::filterY(string s)
{
vector<int> result;
vector<Row>::iterator it;
for(it = d_table.begin(); it != d_table.end(); ++it) {
if(it->getY() == s) {
int val = it->getVal();
result.push_back(val);
}
}
return result;
}
int main()
{
Table t;
t.add("x1", "y1", 1);
t.add("x1", "y2", 2);
t.add("x2", "y1", 3);
t.add("x2", "y2", 4);
vector<int> vx = t.filterX("x1");
vector<int> vy = t.filterY("y2");
vector<int>::const_iterator it;
cout << "Matching X" << endl;
for(it = vx.begin(); it != vx.end(); ++it)
cout << *it << "\t";
cout << endl;
cout << "Matching Y" << endl;
for(it = vy.begin(); it != vy.end(); ++it)
cout << *it << "\t";
cout << endl;
return 0;
}
我尝试了指向成员函数的指针,但因编译器错误而陷入困境。对于以下示例,如果可能的话,我希望有以下 main()
:
int main()
{
Table t;
t.add("x1", "y1", 1);
t.add("x1", "y2", 2);
t.add("x2", "y1", 3);
t.add("x2", "y2", 4);
// instead of filterX, need to pass getX
// to a function named filter
vector<int> vx = t.filter("x1", getX);
vector<int> vy = t.filter("y2", getY);
return 0;
}
最佳答案
成员函数需要一个指向对象实例的指针。也就是说,将 getX
视为 string Row::getX(const Table *this)
。您需要使用实例占位符绑定(bind)
成员函数。
例如使用 tr1,
vector<int> vx = t.filter("x1", std::bind(&Row::getX, std::placeholders::_1));
假设您的过滤器函数已正确定义,绑定(bind)会创建一个接收 Row
对象的仿函数。您应该显示 filter
的代码。我想应该是:
template <class function>
vector<int> Table::filter(const string &s, function f)
{
vector<int> result;
for (vector<Row>::const_iterator it = d_table.begin(), tEnd = d_table.end();
it != tEnd; ++it)
{
if (s == f(*it)) result.push_back(it->getVal());
}
return result;
}
关于c++ - 指向成员函数的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9612582/