2014-12-11 57 views
0

我有一個項目,我必須在每個框中隨機填充一個網格(vector<vector<box>>)與元素,具有特定類型。
我們有4種特定類型:type1,type2,type3type4
用戶設置每種類型的百分比。
實施例: 類型1爲33%,2型22%,類型3 22%,Type4的23%
我們可以有一個這樣的網格:隨機填充一個矢量矢量與固定數量的元素

\----------- 
|1|1|3|3|4|2| 
\----------- 
|4|1|2|2|3|1| 
\----------- 
|4|4|2|1|1|3| 
\------------ 

這裏是我的代碼:

<vector<vector<box>> grid; 
//createGrid is a function initializing a grid with elements with neutral type. 
//in this example the number of lines is 3 and the number of columns is 6 
createGrid(grid,3,6); 
double numberOfType1 = round (3*6*percentOfType1/100); 
//each number is calculated in the same way 
vector<string> types={"Type1","Type2","Type3","Type4"} 
for(int i=0,i<grid.size(),i++){ 
    for(int j=0,j<grid[i].size(),j++){ 
     int choice = rand()%types.size(); 
     if(types[choice]=="Type1"){ 
     grid[i][j]=Element("Type1"); 
     numberOfType1--; 
     if(numberOfType1==0){ 
      //a function that delete the element by its value in the vector 
      delete(types,"Type1"); 
     } 
     }else if(types[choice]=="Type2"){ 
     grid[i][j]=Element("Type2"); 
     numberOfType2--; 
     if(numberOfType2==0){ 
      delete (types,"Type2"); 
     } 
     } //and so on 

我知道我可以使用開關盒,但這是第一份草稿。 所以我的問題是:

  1. 是一個有其他更好的或者更簡單的方法來做到這一點?
  2. 如果沒有,可以改進嗎?
+1

'delete(types,「Type1」);'**'delete' **是一個保留關鍵字,不能用它作爲函數名!詢問代碼時,請至少提供一個[MCVE](http://stackoverflow.com/help/mcve)。此外,如果此代碼實際上在運行,則要求改進或審覈的內容不適用於此網站。 – 2014-12-11 00:53:34

+0

正如@πάνταῥεῖ提到的那樣,'delete'是一個關鍵字。最重要的是,'> grid;'甚至不是有效的(前面的'<'不應該在那裏)。這段代碼甚至不應該編譯,更不用說運行了。 – Cornstalks 2014-12-11 01:20:27

+0

我不清楚你的意思是「類型」。你只是想要向量中的不同值,或者他們應該是不同的類型(通過多態) – 2014-12-11 01:31:19

回答

0

下面是更好/更簡單的方法來做到這一點的建議(需要C++ 11):

std::random_device rd; 
std::mt19937 gen(rd()); 
std::discrete_distribution<> d({3, 2, 2, 2}); //here determine discrete distribution 

std::vector<int> v(10); //or choose different size 
std::generate(std::begin(v),std::end(v),[&](){return d(gen)+1;}); 

DEMO

即產生含有元素如

一個矢量
4 2 1 2 3 3 2 1 3 1 

現在只需將其調整爲您所寫的所需類型即可。