I am creating a prime generator in c++ using an array to store primes as I find them and then use them to check against potentials later. Is there a way to "grow" my array as my program continues?
See std:vector. http://new.cplusplus.com/reference/stl/vector/
I would use a std:vector something like this:
vector<int> primes;
then you would add primes to it by using:
primes.push_back(2);
and retrieve values from the vector by using:
primes[0];
Good luck!
You could use a std::vector template, and use the reserve method based on an upper-bound for the prime counting function.
It sounds like you need a vector to store primes in.
I think your best bet is probably a std::list; whereas a vector needs to reallocate previously stored items when its reserved space is exceeded, this doesn't happen with a list.
The usual cases where this sort of need arises also require an efficient lookup operation. My experience is to go for std::map which makes life much easier than vectors here.
If there is any initially known limit to which you are going to go, you can just calculate the length of the array you need with this simple formula:
let N is that limit and LENGTH is the needed length of the array, so
LENGTH = N / log(N)
where the log(N) is a natural logarithm of N
for more information, see: Prime number distribution theorem.
来源:https://stackoverflow.com/questions/8373708/is-there-a-way-to-grow-my-array-as-my-program-continues