C++生成随机数据方法

生成随机int数组方法(数据未知)

#include "iostream"
#include "time.h"
using namespace std;

int *RandomInit(int range, int count)//给定range数据取值范围,count数组大小
{
    int *num = new int(count);
    int local;
    srand(time(0));
    for (int i = 0; i < count; i++)
    {
        num[i] = (rand() * i) % range;
    }
    for (int i = count; i > 0; i--)
    {
        local = rand() % i;
        if (i - 1 == local)
            continue;
        num[i - 1] += num[local];
        num[local] = num[i - 1] - num[local];
        num[i - 1] = num[i - 1] - num[local];
    }
    return num;
}

生成随机Int序列(给定数据)

#include "iostream"
#include "time.h"
#include "vector"
using namespace std;

void RandomList(vector &num)
{
    int local;
    srand(time(0));
    for (int i = num.size(); i > 0; i--)
    {
        local = rand() % i;
        if (i - 1 == local)
            continue;
        num[i - 1] += num[local];
        num[local] = num[i - 1] - num[local];
        num[i - 1] = num[i - 1] - num[local];
    }
}

生成随机序列(给定数据)--模板函数

#include "iostream"
#include "time.h"
#include "vector"
using namespace std;

template 
void RandomList(vector &list)
{
    int local;
    T tmp;
    srand(time(0));
    for (int i = list.size(); i > 0; i--)
    {
        local = rand() % i;
        if (i - 1 == local)
            continue;
        tmp = list[local];//因为不确定类型,只能用三元交换法.
        list[local] = list[i - 1];
        list[i - 1] = tmp;
    }
}

你可能感兴趣的:(C++生成随机数据方法)