gpt4 book ai didi

c++ - 坚持定义大型二维数组 - C++

转载 作者:行者123 更新时间:2023-11-28 05:34:24 25 4
gpt4 key购买 nike

为了好玩,我正在编写一个使用素数创建图像的程序。为此,我创建了一个包含特定点之前所有自然数的二维数组。

素数在图像中表示为黑色像素,合数表示为白色。该程序适用于小于 1000*1000 的尺寸,但当超过该尺寸时就会卡住。我该如何解决它,任何帮助表示赞赏。

#include <iostream>
#include <cmath>
#include <fstream>

using namespace std;

bool isPrime(long long a){

if(a==1){return false;}

if(a==2){return true;}

if(a%2==0){return false;}

long long root = sqrt(a);
for(long long i=3;i<=root;i+=2){
if(a%i==0){return false;}
}
return true;
}

int main(){
int width = 0, height = 0;
cout << "Which dimentions do you want the picture to be?" << endl;
cout << "Width: " << flush;
cin >> width;
cout << "Height: " << flush;
cin >> height;

/*Create matrix*/
long long imageMap[height][width];
long long numberOfPixels = width*height;
long long i = 1;
long long x = 0 , y = 0;
cout << "Number of pixels the image will have: " << numberOfPixels << endl;

while(i<=numberOfPixels){
imageMap[x][y] = i;
x++;
if(x==width){
y++;
x=0;
}
i++;
}

cout << "Image map done" << endl;
cout << "Creating prime map, please wait..." << endl;


/*Generate prime map*/
int primeMap[width][height]; //The program gets stuck here


for(long long y = 0; y < width; y++){
for(long long x = 0; x < height; x++){
if(isPrime(imageMap[x][y])){
primeMap[y][x] = 1;
} else {
primeMap[y][x] = 0;
}
cout << " x = " << x << flush;
}
cout << endl << "y = " << y << endl;
}

cout << "Writing to file, please wait..." << endl;

/*Write to file*/
ofstream primeImage;
primeImage.open("prime.pbm");

primeImage << "P1 \n";
primeImage << width << " " << height << "\n";

for(int y = 0; y < width; y++){
for(int x = 0; x < height; x++){
primeImage << primeMap[y][x] << " ";
}
primeImage << "\n";
}
primeImage.close();
cout << "Map creation done" << endl;
return 0;
}

最佳答案

如果内存可用,应用程序的默认堆栈大小为 1MB。 Joachim 是正确的,最好的方法是了解 std::vector。但如果这只是一个有趣的一次性程序,您可以简单地增加堆栈大小以使其运行。如果您使用的是 visual studio,请打开项目属性并查看链接器系统选项卡。您可以使用堆栈保留值来增加堆栈大小。但我不建议在实际工作项目中这样做。

顺便说一句:如果 joachim 想重新发布他的评论作为答案,我建议您接受那个。

关于c++ - 坚持定义大型二维数组 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38665411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com