正在尝试对随机[1-100000]长度的矢量进行子矢量化

Trying to Subvectorize Vector of Random [1-100 000] Length

本文关键字:矢量化 随机 1-100000      更新时间:2023-10-16

我正试图将一个可变长度(1-100000)的向量拆分为随机部分以进行进一步的操作。但是我的代码崩溃了,到目前为止,我的调试一直没有结果。有人能提供一些见解吗?

#include <math.h>
#include <vector>
#include <iostream>
using namespace std;
void subVectorize() {
//N ways to pick consecutive integer sequences of length M (M < N) K-Vlaue is Kth smallest number   in sequence
//Task: Find smallest possible subsequence
int M = rand() % (100000 - 1);
vector<int> nVector(M); //Vector to store sequence of variable length
for (int i = 0; i < nVector.size(); i++) //Populate the vector
{
    nVector[i] = i;
}
//Split the vector randomly
vector<int>::const_iterator start = nVector.begin() + (rand() % (100000 - 1));
vector<int>::const_iterator end = nVector.begin() + (rand() % (100000 - 1));
vector<int> subVector(start, end);
}
#include <cmath>
#include <vector>
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void subVectorize( )
{
    //N ways to pick consecutive integer sequences of length M (M < N) K-Vlaue is Kth smallest number   in sequence
    //Task: Find smallest possible subsequence
    int M;
    int randomEnd;
    int randomStart;
    M           = rand( ) % ( 100000 - 1 ) + 1;
    randomEnd   = rand( ) % ( M );
    if( randomEnd == 0 )
    {
        ++randomEnd;
    }
    randomStart = rand() % ( randomEnd );
    vector<int> nVector(M); //Vector to store sequence of variable length
    for ( unsigned int i = 0 ; i < nVector.size( ) ; i++ ) //Populate the vector
    {
        nVector[i] = i;
    }
    //Split the vector randomly
    vector<int>::const_iterator start   = nVector.begin() + randomStart;
    vector<int>::const_iterator end     = nVector.begin() + randomEnd;
    vector<int> subVector( start , end );
}
int main()
{
    srand( time( NULL ) );
    subVectorize( );
    return 0;
}

如果你这样调整,它应该可以正常工作。

我已经包含了伪随机种子。

基本上,你的问题是startend都可能超出范围,end可能在start之前,如果M是0呢?你不能创建一个大小为0的向量,而且你的代码无论如何都会访问它,这对0向量不起作用。

rand( ) % ( 100000 - 1 ) + 1

+1是一个偏移量,这意味着它将是你的伪随机数+1,因此它不可能是0。