Boundless Arrays?

跟風遠走 提交于 2019-12-11 06:18:49

问题


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>
#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]);
    }
}
}

回答1:


Yes. Use a std::vector or std::deque.




回答2:


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.




回答3:


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/




回答4:


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.



来源:https://stackoverflow.com/questions/4741436/boundless-arrays

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