vector count function C++

18,407

Solution 1

The documentation of std::count says:

Returns the number of elements in the range [first,last) that compare equal to val.

so you should use something along the lines of the following, to get the number of prime numbers:

int cnt = count(vec_prime_number.begin(), vec_prime_number.end(), 1);

as you can see.

Solution 2

"Ideally, I would like to make it so that vec has {5, 7, 13, 17} //in other words, only prime numbers in it"

You don't need to count simply use :

bool IsPrime (int i) 
{ 
  /*returns true, if i is Prime */
}

vec.erase(std::remove_if(vec.begin(), vec.end(), IsPrime), vec.end());
Share:
18,407
Mdjon26
Author by

Mdjon26

Updated on June 04, 2022

Comments

  • Mdjon26
    Mdjon26 over 1 year

    I have a vector

    vector<int> vec;
    

    it's storing random numbers {5, 7, 8, 9, 13, 15, 17}

    and I have a vector that is evaluating the previous vector's numbers as 1 or 0 if they are a prime number or not

    vector< int> vec_prime_number;
    

    so for the previous it would be {1, 1, 0, 0, 1, 0, 1}

    I'm trying to use the count function to save only the prime numbers in it. And I'm having some problems with doing it.

    Ideally, I would like to make it so that vec has {5, 7, 13, 17} //in other words, only prime numbers in it

    I've tried stuff like

    int cnt = count(vec.begin(), vec.end(), vec_prime_number())
    

    but I can't get any of it to work. Any ideas on how to get count to store only the prime numbers?