如何使用三参数化构造函数的rand()函数初始化对象数组?

时间:2018-02-13 14:49:07

标签: c++ arrays

这是一个从数组中查找最大和最小Box的程序。如何自动生成随机数并将其存储在数组中?

如何自动生成长度,宽度和高度并将其存储在对象数组中?

#include <iostream>
#include <stdlib.h>

using namespace std;

 class Box{
private:
    double length;
    double height;
    double width;
    //parameterized constructor for the Box class to initialized length, height and width
    public:
    Box(double ilength,double iheight,double iwidth){
    length=ilength;
    height=iheight;
    width=iwidth;
    }

    //calculate the volume
    double getvolume(){
    return length*height*width;
    }
    //calculate the width
    double getarea(){
    return 2*width*length+2*length*height+2*height*width;
    }


};



int main()
{
//Generate the value of length, height and width of every box
double e=(rand()%6)+1;
double f=(rand()%6)+1;
double g=(rand()%6)+1;
double i=(rand()%7)+1;
double j=(rand()%8)+1;
double k=(rand()%9)+1;
double l=(rand()%10)+1;
double m=(rand()%11)+1;
double n=(rand()%12)+1;

cout<<e<<"this is e"<<endl;
cout<<f<<"this is f"<<endl;
cout<<g<<"this is g"<<endl;
cout<<i<<"this is i"<<endl;
cout<<j<<"this is j"<<endl;
cout<<k<<"this is k"<<endl;
cout<<l<<"this is l"<<endl;
cout<<m<<"this is m"<<endl;
cout<<n<<"this is n"<<endl;

Box b[3]={Box(e,f,g),Box(i,j,k),Box(l,m,n)};

double c,d,h,a;
c=b[1].getvolume();
d=b[1].getarea();
h=b[0].getvolume();
a=b[0].getarea();


cout << c <<endl;
cout<< d<<endl;
return 0;
}

这有效,但是还有另外一种方法吗?

1 个答案:

答案 0 :(得分:0)

如果所有盒子的模数值都相同,我会做类似的事情:

#include <algorithm>    
Box b[3]; 
std::generate(std::begin(b), std::end(b), []()mutable{return Box(rand()%6+1, rand()%7+1, rand()%8+1);});

您需要将默认构造函数添加到Box类:

Box() = default;