Boundless Arrays?
I'm having some trouble. I wrote a code to find prime numbers up to a number, but for some reason, it gives me the error that I didn't define the number of elements in the array that I will be using. Is it possible to have an array where the number of elements isn't limited? Thanks :)
#include <iostream>
#include <cmath&开发者_Go百科gt;
#include <fstream>
#include <cstdlib>
using namespace std;
int primer(int max);
int main()
{
system("pause");
return 0;
primer(1000);
}
int primer(int max){
int a[]=2;
for (int i=2;i<=max;i++){
prime=true;
for (int ii=1;ii<=#a;ii++) {
if i/a[ii]==math.floor(i/a[ii]) {
prime=false;
}
}
if prime==true {
a[#a+1]=i;
}
}
for (i=1;i<=#a;i++) {
print(a[i]);
}
}
}
Yes. Use a std::vector
or std::deque
.
What is this # symbol that you're using everywhere?
Your line int a[]=2
is incorrect.
You need to specify how big your array is going to be. For example, int a[100]
, or
int a[] = {Values here}
.
That being said, you probably want a flexibly sized array like the vector class.
The compiler needs to know how much space to allocate, and therefore requires you to state how many elements you have.
You could try using the STL vector instead of an array. This allows you to add as many elements as you want, without declaring the number right at the beginning.
http://www.cplusplus.com/reference/stl/vector/vector/
You are always 'limited', if only by the amount of memory which can allocate for the array.
Having said that, you will probably be fine using a std::vector
.
精彩评论