我试图将变量(1 - 100 000)长度向量分成随机部分以便进一步操作。但是我的代码崩溃了,到目前为止,我的调试没有结果。任何人都可以提供任何见解吗?
#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);
}
答案 0 :(得分:1)
#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;
}
如果你这样调整它,它应该可以正常工作。
我已经包含了伪随机种子。
基本上您的问题是,start
和end
都可能超出范围而end
可能在start
之前,如果M
为0则会出现问题?你不能创建一个大小为0的向量,你的代码无论如何都要访问它,这对于0 Vector来说是不行的。
rand( ) % ( 100000 - 1 ) + 1
+1是一个偏移量,这意味着它将是你的伪随机数+1,因此它不能为0.