【发布时间】:2014-12-11 00:44:09
【问题描述】:
我有一个项目,我必须在每个框中随机填充具有特定类型的元素的网格 (vector<vector<box>>)。
我们有 4 种特定类型:type1、type2、type3 和 type4。
用户设置每种类型的百分比。
例子 :
类型1 33%,类型2 22%,类型3 22%,类型4 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
我知道我可以使用开关盒,但这是初稿。
所以我的问题是:
- 还有其他更好或更简单的方法吗?
- 如果没有,是否可以改进?
【问题讨论】:
-
delete(types,"Type1");delete是保留关键字,不能作为函数名使用!询问代码时,请至少提供MCVE。此外,如果此代码确实有效,则要求改进或审查对于本网站来说是题外话。 -
正如@πάνταῥεῖ 提到的,
delete是一个关键字。最重要的是,<vector<vector<box>> grid;甚至无效(前面的<不应该在那里)。这段代码甚至不应该编译,更不用说运行了。 -
我不清楚您所说的“类型”是什么意思。您只是想要向量中的不同值还是它们实际上应该是不同的类型(通过多态性)