问题
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?
回答1:
See std:vector. http://new.cplusplus.com/reference/stl/vector/
回答2:
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!
回答3:
You could use a std::vector
template, and use the reserve
method based on an upper-bound for the prime counting function.
回答4:
It sounds like you need a vector to store primes in.
回答5:
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.
回答6:
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.
回答7:
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