[英]How to make an object take and store an Array of arbitrary, but compile-time known size?
[英]How to declare an array without size known at compile-time?
我正在嘗試實現random_function()
,它輸出范圍內(用戶輸入)內的隨機數的數量,以及count_function()
來計算用戶想要在輸出的隨機數中查找的值。 我將隨機數保存在一個名為randomlist[]
的數組中,以便它可以用於計算輸出隨機數的值。 但是,我不能在 header 文件中聲明一個沒有固定大小的數組,並在 count_function.cpp 中定義它的大小。 所以我不能在count_function()
中使用randomlist[]
而不重新定義它(這是沒有意義的......)。
有沒有辦法在 header 文件中聲明數組而不定義其大小?
#pragma once
using namespace std;
class Rand
{
public:
// Rand();
int range,min,max;
char key;
void Random_function();
void Count_function();
// randomlist[]; something like this, which that is not possible in c++
};
#include <iostream>
#include "random_function.hpp"
using namespace std;
void Rand::Random_function()
{
beginning:
cout << "Enter amount of numbers to generate: ";
cin >> range;
if (range<=0 || cin.fail())
{
cout <<"Error! Please enter valid number and try again! "<<endl;
goto beginning;
}
else
{
reenter:
cout << "Enter minimum boundary: ";
cin >> min;
cout << "Enter maximum boundary: ";
cin >> max;
cout << "\n";
srand((unsigned)time(NULL));
if(max<min || cin.fail())
{
cout << "\nError! Please enter the valid value and try again! " << endl;
goto reenter;
}
else
{
int randomlist[range]; //I defined the size of the randomlist here but I want to use this outside of the random_fucntion() as well.
for(int i=0 ; i < range; i++)
{
randomlist[i] = min + (rand() % static_cast<int>(max - min + 1));
cout <<i+1<<". "<< randomlist[i] <<endl;
}
}
cout <<"\n"<< "Total random numbers generated: " << range<< endl;
cout <<"Do you want to continue? y/n"<<endl;
cin >> key;
if(key=='y')
{
Count_function();
cout <<"Do you want to restart? y/n"<<endl;
cin >> key;
if(key=='y')
{
goto beginning;
}
else
{
exit(0);
}
}
else
{
cout <<"Do you want to restart? y/n"<<endl;
cin >> key;
if(key=='y')
{
goto beginning;
}
else
{
exit(0);
}
}
}
}
void Rand::Count_function()
{
int n,count=0;
reenter2:
cout<<"Enter the value to count for: ";
cin>>n;
if(cin.fail())
{
cout<<"Please enter valid value to count for"<<endl;
goto reenter2;
}
else
{
for(int i=0 ; i <range; i++)
{
if(randomlist[i]==n)
{
count++;
}
}
}
cout <<"The number of '"<<n<<"'s in the given list is: "<< count <<endl;
}
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <random>
#include "random_function.hpp"
using namespace std;
int main()
{
Rand call;
call.Random_function();
}
當您想使用數組,但在編譯時無法知道大小時,C++ 中普遍接受的方法是使用std::vector
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.