Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter object in c++ [duplicate]

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).

like image 758
user6320378 Avatar asked Nov 30 '22 23:11

user6320378


1 Answers

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; });
like image 146
Sander De Dycker Avatar answered Dec 13 '22 02:12

Sander De Dycker