I am trying to generalize the functions filterX()
and filterY()
in the following class Table
to function filter()
.
The functions filterX()
and filterY()
only differ in the function they call inside the procedure. While filterX()
calls getX()
, filterY()
calls 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;
}
I tried pointer to member function but got bogged down by compiler errors. For the following example, I would like to have the following main()
if that is possible:
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;
}