push_back for vector not adding all the elements from for loop after boolean expression using lambda function - c++

Viewed 60

I have to insert a number into a vector after a certain Boolean condition has been met. My code is only adding the first expression but not the others:

vector<int> f(int n){

    vector<int> p;

    for(int i = 2; i < n; ++i){
    
        if(all_of(p.begin(), p.end(), [&](int pn){ return pn % i == 0; }))
            p.push_back(i);
    }
    return p;
}

int main(){
    auto v = f(30)
    copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
}

I only get the first number added to the vector but not the rest. Any idea where the code has gone wrong ?

1 Answers

You add the single 2 in the first loop iteration, then i > 2 and the predicate 2 % i == 0 is 2 == 0, is always false. Therefore the resulting vector p gets the single element { 2 }.

Related