简体   繁体   English

如何将值从不同的多个数组传递到新的单个数组?

[英]How can I pass values from different multiple arrays to a new single array?

My code:我的代码:

void Block::word()
{
    std::string worda[] = {"cat","owl","cow"};
    std::string wordb[] = {"apple","power","block"};
    std::string wordc[] = {"account","extreme","kingdom"};
    std::string wordd[] = {"adjective","undefined","pineapple"};

    srand(time(0));
    fnwords[0] = worda[rand() % 3 + 1];
    fnwords[1] = wordb[rand() % 3 + 1];
    fnwords[2] = wordc[rand() % 3 + 1];
    fnwords[3] = wordd[rand() % 3 + 1];

    for (int d=0; d<4; d++){
          std::cout << fnwords[d] << std::endl;
      }
}

int main()
{
    Block obj;
    obj.word();
    return 0;
}

Here the first index of array fnwords must contain a random word from array worda , second index from wordb , and so on.这里阵列的第一索引fnwords必须包含从阵列的随机字worda ,第二索引从wordb ,依此类推。

But it gives error sometimes that program.exe has stopped working.但有时它会出错,program.exe 已停止工作。

And it initializes array like this:它像这样初始化数组:

-cow
-cat
-kingdom
-undefined

The problem seems to be related to rand() call.问题似乎与rand()调用有关。 You are using arrays with length of 3. However, rand()%3 returns one of the following set: {0, 1, 2} which are the only valid values to index your array.您正在使用长度为 3 的数组。但是, rand()%3返回以下集合之一:{0, 1, 2} 这是唯一可以为您的数组建立索引的有效值。 When you +1 to this index, it gives you {1, 2, 3} where index 3 is an invalid index.当您对该索引+1 ,它会给您 {1, 2, 3} ,其中索引 3 是无效索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将多个堆数组传递给新线程? - How do I pass multiple heap arrays to a new thread? 如何将值从数组传递到构造函数? C ++ - How can I pass values from an array to the constructor? C++ 如何在 C++ 中列表的单个位置插入多个不同的值? - How can i insert multiple different values in single position of list in c++? 如何创建具有不同字符 arrays 的多个 class 实例? - How can I create multiple class instances with different character arrays? 如何创建以char作为键值和字符串数组作为映射值的映射-数组的长度必须不同? - How can I create a map with chars as key values and arrays of strings as mapped values - arrays must be of different length? 如何将多个函数重载作为单个参数传递? - How can I pass multiple function overloads as a single argument? 如何简洁地将单个变量与许多不同的值进行比较? - How can I concisely compare a single variable to many different values? 如何从多个 arrays 中绘制多个随机变量? - How can i draw multiple random variables from multiple arrays? 如何将数组数组传递给函数? - How do I pass an array of arrays to a function? 如何将逗号分隔的值传递到多维数组? - How can i pass comma separated values into a multidimensional array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM