【问题标题】:Randomly fill a vector of vector with a fix number of elements用固定数量的元素随机填充向量的向量
【发布时间】:2014-12-11 00:44:09
【问题描述】:

我有一个项目,我必须在每个框中随机填充具有特定类型的元素的网格 (vector<vector<box>>)。
我们有 4 种特定类型:type1type2type3type4
用户设置每种类型的百分比。
例子 : 类型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

我知道我可以使用开关盒,但这是初稿。 所以我的问题是:

  1. 还有其他更好或更简单的方法吗?
  2. 如果没有,是否可以改进?

【问题讨论】:

  • delete(types,"Type1"); delete 是保留关键字,不能作为函数名使用!询问代码时,请至少提供MCVE。此外,如果此代码确实有效,则要求改进或审查对于本网站来说是题外话。
  • 正如@πάνταῥεῖ 提到的,delete 是一个关键字。最重要的是,&lt;vector&lt;vector&lt;box&gt;&gt; grid; 甚至无效(前面的 &lt; 不应该在那里)。这段代码甚至不应该编译,更不用说运行了。
  • 我不清楚您所说的“类型”是什么意思。您只是想要向量中的不同值还是它们实际上应该是不同的类型(通过多态性)

标签: c++ random vector


【解决方案1】:

这里有一个更好/更简单的方法的建议(需要 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  

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 2013-09-08
    相关资源
    最近更新 更多