需要将1-100的随机数插入三维数组中

时间:2015-11-04 21:31:57

标签: c++ arrays

我需要创建一个程序,其中1到100之间的随机数放在3D数组的每个维度中。这些数组具有不同的大小,因此到目前为止只在执行时遇到崩溃。尝试使用一维阵列进行小规模测试并使其正常工作。似乎无法在更大范围内进行翻译。我的代码到目前为止......

int const STOCK_AMOUNT = 1000, DAY_AMOUNT = 366, TIME_AMOUNT = 480;
int randomGenerator();
void randomInsert(int array0[DAY_AMOUNT][TIME_AMOUNT][STOCK_AMOUNT]);

int main()
{
    int cube[DAY_AMOUNT][TIME_AMOUNT][STOCK_AMOUNT];
    srand((unsigned)time(0));
    randomInsert(cube);
    return 0;
}

void randomInsert(int array0[DAY_AMOUNT][TIME_AMOUNT][STOCK_AMOUNT])
{
    for (int count1 = 0; count1 < DAY_AMOUNT; count1++)
    {
        for (int count2 = 0; count2 < TIME_AMOUNT; count2++)
        {
            for (int count3 = 0; count3 < STOCK_AMOUNT; count3++)
            {
                int randomGenerator();
                array0[count1][count2][count3] = randomGenerator();
                cout << endl;
            }
        }
    }   
}

int randomGenerator()
{
    int randNum;
    int lowerLimit = 1;
    int upperLimit = 100;
    randNum = (rand() % upperLimit) + lowerLimit;
    return randNum;
}

3 个答案:

答案 0 :(得分:3)

你似乎超过了堆栈大小。在堆栈上创建的数组包含大约175M的整数,即大约700MB的内存。您需要设置编译选项以增加堆栈大小。

编辑:此外,请注意,将如此庞大的数组放在堆栈上通常被视为不良做法。理想情况下,使用STL向量,这是处理数组的现代方法。

答案 1 :(得分:1)

这是使用STL的更复杂的版本:

#include <cassert>
#include <cstddef>
#include <cstdint>
#include <ctime>
#include <functional>
#include <iostream>
#include <random>

using std::cout;
using std::endl;

// The size of a type that can hold values from 1 to 100.  Used for storage.  (Copy to int for calculation.)
using elem_t = int_least8_t;
// Lower and upper bounds:
constexpr int lb = 1;
constexpr int ub = 100;

constexpr size_t stocks = 100, days = 300, times = 400;
using pricearray_t = elem_t[days][times][stocks];

pricearray_t& init_prices()
/* Returns a heap-allocated array that must be deleted with delete[]. */
{
  // This ugly little cast is brought to us by the C++ rules for array types.
  pricearray_t &to_return = *(pricearray_t*) new pricearray_t;
  const std::default_random_engine::result_type seed = std::time(NULL) * CLOCKS_PER_SEC + std::clock();
  std::default_random_engine generator(seed);
  std::uniform_int_distribution<int_fast8_t> distribution( lb, ub );

  auto x = std::bind( distribution, generator );

  for ( size_t i = 0; i < days; ++i )
    for ( size_t j = 0; j < times; ++j )
      for ( size_t k = 0; k < stocks; ++k )
        to_return[i][j][k] = static_cast<elem_t>(x());

  return to_return;
}

int main(void)
{
  const pricearray_t &prices = init_prices();

  long long int sum = 0;
  for ( size_t i = 0; i < days; ++i )
    for ( size_t j = 0; j < times; ++j )
      for ( size_t k = 0; k < stocks; ++k ) {
        const int x = prices[i][j][k];
        assert( x >= lb );
        assert( x <= ub );
        sum += x;
      }

   cout << "The mean is " << static_cast<double>(sum) / days / times / stocks << "." << endl;

  delete[] &prices;
  return EXIT_SUCCESS;
}

这是一个使用智能指针自动管理内存的版本:

#include <cassert>
#include <cstddef>
#include <cstdint>
#include <ctime>
#include <functional>
#include <iostream>
#include <memory>
#include <random>

using std::cout;
using std::endl;

// The size of a type that can hold values from 1 to 100.  Used for storage.  (Copy to int for calculation.)
using elem_t = int_least8_t;
// Lower and upper bounds:
constexpr int lb = 1;
constexpr int ub = 100;

constexpr size_t stocks = 100, days = 300, times = 400;
// The unique_ptr type doesn’t play nicely with arrays of known size.
using pricearray_t = elem_t[][times][stocks];

std::unique_ptr<pricearray_t> init_prices()
/* Returns a managed pointer to an array of uniformly-distributed values.
 */
{
  // This smart pointer will use its move constructor to avoid copying the entire array.
  std::unique_ptr<pricearray_t> to_return = std::make_unique<pricearray_t>(days);
  const std::default_random_engine::result_type seed = std::time(NULL) * CLOCKS_PER_SEC + std::clock();
  std::default_random_engine generator(seed);
  std::uniform_int_distribution<int_fast8_t> distribution( lb, ub );
  auto x = std::bind( distribution, generator );

  for ( size_t i = 0; i < days; ++i )
    for ( size_t j = 0; j < times; ++j )
      for ( size_t k = 0; k < stocks; ++k )
        to_return[i][j][k] = static_cast<elem_t>(x());

  return to_return;
}

int main(void)
{
 /* The contents of the smart pointer will be deleted automatically when it goes out of scope.
  */
  const std::unique_ptr<pricearray_t> prices = init_prices();

  long long int sum = 0;
  for ( size_t i = 0; i < days; ++i )
    for ( size_t j = 0; j < times; ++j )
      for ( size_t k = 0; k < stocks; ++k ) {
        const int x = prices[i][j][k];
        assert( x >= lb );
        assert( x <= ub );
        sum += x;
      }

   cout << "The mean is " << static_cast<double>(sum) / days / times / stocks << "." << endl;

   return EXIT_SUCCESS;
 }

答案 2 :(得分:0)

似乎教授提供的原始立方体的规格显然太大了......奇怪的是教授怎么会抓住它?缩减规格,现在有一些有用的东西。主要的位应该是每天(50)找到每天股票价格的平均值(50)。

#include<iostream>
#include<ctime>
#include <cstdlib>
#include <fstream>
using namespace std;
const int STOCK_AMOUNT = 100, DAY_AMOUNT = 50, TIME_AMOUNT = 8;
int randomGenerator();
void priceGenerator(int [STOCK_AMOUNT][DAY_AMOUNT][TIME_AMOUNT]);


int main()
{
ofstream outputFile;
int cube[STOCK_AMOUNT][DAY_AMOUNT][TIME_AMOUNT];
double total;
srand((unsigned)time(0));
priceGenerator(cube);
outputFile.open("Average_Day_Price");
for (int row = 0; row < STOCK_AMOUNT; row++)
{   
total=0;
for (int col = 0; col < DAY_AMOUNT; col++)
{       
for (int layer = 0; layer < TIME_AMOUNT; layer++)
{           
total = cube[row][col][layer];
double average = (total / TIME_AMOUNT);
outputFile << "STOCK Id:" << (row+1) << "--" << "--" << average <<endl:             
}
}
}
outputFile.close();
return 0;
}
void priceGenerator(int array0[STOCK_AMOUNT][DAY_AMOUNT][TIME_AMOUNT])
{
int i,y, z;
for ( i = 0; i < STOCK_AMOUNT; i++)
{
for ( y = 0; y < DAY_AMOUNT; y++)
{
for (z = 0; z < TIME_AMOUNT; z++)       
{
int randNum;
int lowerLimit = 1;
int upperLimit = 100;
randNum = (rand() % upperLimit) + lowerLimit;
array0[i][y][z] = randNum;          
}
}
}
}