C++ 创建一个包含数字数组的对象,然后将其存储在向量c++;
因此,我有一个名为numbers的类,它接受一个数字数组并将它们洗牌,然后打印出新的数组 我想做的是,然后将新数组作为对象返回,并以“number”类型的向量推回该对象。 这是我的密码:C++ 创建一个包含数字数组的对象,然后将其存储在向量c++;,c++,C++,因此,我有一个名为numbers的类,它接受一个数字数组并将它们洗牌,然后打印出新的数组 我想做的是,然后将新数组作为对象返回,并以“number”类型的向量推回该对象。 这是我的密码: class numbers { private: static int indexCount; //vector <vector <int> > list; //vector<int> temp; int j; publi
class numbers
{
private:
static int indexCount;
//vector <vector <int> > list;
//vector<int> temp;
int j;
public:
void swap (int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int randomize (int arr[], int n)
{
indexCount=0;
for (int i = n -1; i > 0; i--)
{
j = rand() % (i + 1);
indexCount++;
swap(&arr[i], &arr[j]);
}
}
void printArray (int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << "random calls: " << indexCount <<endl;
}
};
类号
{
私人:
静态int索引计数;
//向量表;
//向量温度;
int j;
公众:
无效交换(int*a,int*b)
{
int temp=*a;
*a=*b;
*b=温度;
}
int随机化(int arr[],int n)
{
indexCount=0;
对于(int i=n-1;i>0;i--)
{
j=rand()%(i+1);
indexCount++;
掉期交易(&arr[i]、&arr[j]);
}
}
无效打印数组(int arr[],int n)
{
对于(int i=0;i cout好的,关于stdib的几个提示:std::swap、std::sort、std::shuffle(示例):
随机范围[a;b)示例:
模板
内联T uniformRandom(T低=静态转换(0.),T高=静态转换(1.))
{
静态_断言(std::is_floating_point::value,“T必须是浮点1”);
std::随机_装置rd;
标准:mt19937 gen(rd());
标准:均匀实分布图(低、高);
返回dis(gen);
}
所以你实际上不需要任何额外的类。你可以有数值向量,并在上面使用std函数。
好吧,如果你真的想要一个类,只要把这个向量和对stdlib的调用放在这个新类中
int main()
{
vector <numbers> list;
srand (time(NULL));
numbers num;
int arr[] = {1, 2, 3, 4, 5, 6, 0, 0, 0};
int n = sizeof(arr) / sizeof(arr[0]);
num.randomize(arr,n);
num.printArray(arr,n);
list.push_back(num);
return 0;
}
std::shuffle(tmp_buffer.begin(), tmp_buffe.end(), std::mt19937(std::random_device()()));
template <class T = float>
inline T uniformRandom(T low = static_cast<T>(0.), T hi = static_cast<T>(1.))
{
static_assert (std::is_floating_point<T>::value, "T must be floating point one.");
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<T> dis(low, hi);
return dis(gen);
}