Functor in copy_if

04/22/2017 12:05 Dwarfche#1
Hey, I need some help with a functor in C++ for the copy_if algorithm. PM me if you can help, thanks in advance
04/22/2017 12:16 Jeoni#2
I may help, but why not describing the problem in the thread, so anyone can participate and the solution may help others, too?
If that is not possible due to legal reason (your project is top secret), try breaking the error down to a simple case which has nothing to do with your project anymore.
With best regards
Jeoni
04/22/2017 12:54 Dwarfche#3
Okay, I have list of pointers to objects of class CEstate. CEstate is an abstract class which is inherited by CPlot,CHouse and CFlat.

I have to make a function that returns a list of all objects that are from a city(parameter of the function). It should be done with copy_if.

list<CEstate*> listByTown(string town){
copy_if(estateList.begin(), estateList.end(), listByTown.begin(), ?);
}
04/22/2017 13:17 Jeoni#4
I guess the most simple version is passing a lambda function which does the town check.
Code:
std::copy_if(estateList.begin(), estateList.end(), result.begin(), [&town](CEstate* estate) -> bool { estate->town == town; });
The lambda (and therefor the check) is called for each object in estateList. The town-member is just made up, but I guess the class includes something like this. And town (not the member) is the argument passed to the listByTown function as already done in your example.
With best regards
Jeoni
04/22/2017 14:10 Dwarfche#5
That's what I wrote:
Code:
std::copy_if(estateList.begin(), estateList.end(), listByTown.begin(), [&town](CEstate* estate) -> bool { return estate->getAddress() == town; });
I got error: list iterator not incrementable.
The error appears when I run the program.
04/22/2017 14:15 Jeoni#6
Is your result list (listByTown) big enough to hold the objects? Since copy_if do not change the size of the result list, it has to be allocated before.
With best regards
Jeoni
04/22/2017 14:18 Dwarfche#7
I did not allocate it before. just declared it
04/22/2017 14:35 th0rex#8
Code:
std::copy_if(estateList.begin(), estateList.end(), std::back_inserter(listByTown), [&town](CEstate* estate) -> bool { return estate->getAddress() == town; });
should work as long as listByTown has a push_back method.
04/22/2017 14:48 Dwarfche#9
Is there any way to reserve memory for X elements? Like the reserve method for vectors?
And yes, the list should have push_back method, since it's already defined. Still it doesnt work if my list size is less or more than the actual number of objects from the desired town.