Let's say I have a class:
class Cell {
int ID;
int valueX;
int valueY;
};
and in main() I declared vector of Cells:
vector<Cell> myCells;
My problem is to write a function that gets vector of Cells, operator (gt - greater than, le - less or equal, and so on), name of a variable and an integer, and returns vector of Cells that meets the requirement? For example:
vector<Cells> resultCells = filter(myCells, gt, valueX, 5)
is vector of Cells where each cell has valueX greater than 5.
My first attempts required a lot of ifs and switches and I'm sure it's not proper solution. Then I asked a friend for a tip, he told me about things like functors, lambdas, std::function, std::map, std::bind, that can help me to do this and I've read about it but I am unable to use in in practise.
One of examples that I've seen on the Internet is this one, but it's less complex and hard to reuse (for me).
Try something like this using std::copy_if
:
std::vector<Cell> resultCells;
std::copy_if(myCells.begin(), myCells.end(),
std::back_inserter(resultCells),
[](const Cell& c) { return c.valueX > 5; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With