2014-10-18 54 views
0

我試圖將一個變量(1 - 100 000)長度矢量分成隨機部分進一步操作。但是我的代碼崩潰了,到目前爲止,我的調試沒有結果。誰能提供任何見解?試圖Subvectorize矢量的隨機[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); 

} 
+4

你'start'可以end'後'而且兩者可以同時出的範圍。 – 2014-10-18 01:43:19

+0

剛剛發現並應用了一個修復程序 - 我想!仍試圖找出隨機性;我想我需要種下它?沒有時間庫,有沒有辦法做到這一點? – 2014-10-18 01:56:02

+0

如果我能夠幫助你,請通過接受我的回答告訴我,或者更新你的問題。此外,如果您找到可能不同的解決方案,包括它可以幫助其他人找到解決問題的正確解決方案。 – deW1 2014-10-28 21:57:46

回答

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; 
} 

,如果你調整它這樣,它應該工作的罰款。

我已經包含了僞隨機種子。

基本上你的問題是該startend可能都超出範圍和end可能是以前start還要是M是0?你不能創建一個大小爲0的矢量也無論如何你的代碼訪問它不會爲0矢量工作。

rand() % (100000 - 1) + 1 

+1是偏移,這意味着它將會是你的僞隨機數+ 1,因此它不能爲0

+0

我選擇以與subvectorization不同的方式處理此問題,但是您的帖子很有幫助,所以我會接受它。我對延遲表示歉意! – 2014-10-29 23:09:25