Charlotte45
Charlotte45

Reputation: 143

Filter operation from vector to vector

I'm trying to implement a filter operation which takes a vector V and creates another vector D with the filtered elements of V. The result can't be a pointer and I'm not allowed to use a regular for loop/while. I was thinking of using: for_each, copy, copy_if but none seem to work.

    vector<Car> fin;
    vector<Car> all(repo->getAll());
    for_each(all.begin(), all.end(), [=]( Car& cc) {
            if ( cc.getModel() == model) {
               Car c(cc.getNumber(),cc.getModel(),cc.getCategory());
                fin.push_back(c);
            }

This will give me an error when performing the push_back.

copy_if(all.begin(), all.end(),fin.begin(),
                [&](const Car& cc) { if (cc.getModel()==model) return cc; });

This will go inside the iterator library and give me errors along with "Conditional expression of type const Car is illegal"

Is there any way to make copies of the elements I need from one vector and add them to the other inside a loop like this?

I tried if(find_if(...) on the same idea, with a lambda and trying to create a new Car and eventually add it to my D vector but it didn't work either

Full corected filter function:

vector<Car> Controller::filterByCategory(string category) {
    vector<Car> fin;
    vector<Car> all(repo->getAll());

    copy_if(all.begin(), all.end(),fin.begin(),
                [&](Car& cc) { return (cc.getCategory()==category); });
    return fin;
}

Upvotes: 0

Views: 147

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

This will go inside the iterator library and give me errors along with "Conditional expression of type const Car is illegal"

Your lambda function is expected to return a boolean value, not an object. Change it to

copy_if(all.begin(), all.end(),fin.begin(),
                [&](const Car& cc) { 
                    return (cc.getModel()==model); });

It's meant to be used as the condition by the copy_if() if an item from the input range should be copied to the result or not.

Upvotes: 4

W.F.
W.F.

Reputation: 13988

for_each would also work if you use [&] in the lambda expression and also provide copy constructor in your Car class.

Upvotes: 0

Related Questions