Is there a way to “grow” my array as my program continues?

不羁的心 提交于 2019-12-01 22:52:27

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!