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

2020-04-16 18:03发布

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?

标签: c++ types primes
7条回答
Juvenile、少年°
2楼-- · 2020-04-16 18:39

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!

查看更多
\"骚年 ilove
4楼-- · 2020-04-16 18:46

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.

查看更多
姐就是有狂的资本
5楼-- · 2020-04-16 18:50

You could use a std::vector template, and use the reserve method based on an upper-bound for the prime counting function.

查看更多
我命由我不由天
6楼-- · 2020-04-16 18:50

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.

查看更多
啃猪蹄的小仙女
7楼-- · 2020-04-16 18:52

It sounds like you need a vector to store primes in.

查看更多
登录 后发表回答