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

How can i initialize array of object with rand() function of a three parameterized constructor?

本文关键字:函数 rand 初始化 数组 对象 构造函数 参数 何使用 三个      更新时间:2023-10-16

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

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

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

这有效,但是还有另一种比这更好的方法吗?

如果对所有盒子的模量值都相同,我会做这样的事情:

#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() = default;