There are basically 2 possible solutions.
- You can either erase none prime values from the
std::vector
- or copy just prime values to a new
std::vector
For both solutions it is necessary to have a function, which detects, if a number is a prime or not. There are tons of such functions in the internet. Please select the best for your requirements.
Then, you need to think, if the erase/remove_if or the copy_if solution is better for you.
With erase/remove_if you are shifting a lot of memory, so, if you use it, then maybe better to start from the end.
On the other hand, copy_if may also invoke memory reallocation and copying, because of push_back and back_inserter actions.
So, sorry to say, it depends . . .
Please see below an example with both solutions.
#include <iostream>
#include <vector>
#include <algorithm>
// Some of the many isPrime functions, available in the internet
// Basically, for this example, it does not matter which
bool isPrime(int number){
if(number < 2) return false;
if(number % 2 == 0) return false;
for(int i=3; (i*i)<=number; i+=2)
if(number % i == 0 ) return false;
return true;
}
// Version with erase/remove idiom
// Yes, no reference for input parameter. Data shall be copied
auto primeVector1(std::vector<int> data) {
// Remove all none primes
data.erase(std::remove_if(data.begin(), data.end(), [](const int i){ return not isPrime(i);}),data.end());
return data;
}
// Version with copying prime data to new vector
auto primeVector2(std::vector<int>& data) {
std::vector<int> result{};
// Copy primes to new vector
std::copy_if(data.begin(), data.end(), std::back_inserter(result), [](const int i){ return isPrime(i);});
return result;
}
// Test/Driver code
int main() {
std::vector test{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23};
for (const int i : primeVector1(test)) std::cout << i << ' '; std::cout << '\n';
for (const int i : primeVector2(test)) std::cout << i << ' '; std::cout << '\n';
}