2014-12-11 98 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 

现在只需将其调整为您所写的所需类型即可。