srand无法正常工作

时间:2017-09-14 23:38:11

标签: c++ vector random srand

我正在编写一个程序,需要使用2个不同的种子列表填充两个带有随机整数(小于1000)的向量。当我尝试使用srand与我应该使用的种子它给我一个非常奇怪的输出。

这是我到目前为止编写的代码......

 #include <iostream>
 #include <vector>
 #include <algorithm>
 #include <cstdlib>
 #include <ctime>
 using namespace std;

 void Vectors(vector <int> v1, vector <int> v2, int s1, int s2) {
     srand(s1);
     for (int i = 0; i < 200; i++) {
        v1.push_back(rand () % 1000 + 1);
        //v1[i] = rand() % 1000 + 1;
     }
     srand(s2);
     for (int i = 0; i < 100; i++) {
         v2.push_back(rand() % 1000 + 1);
         //v2[i] = rand() % 1000 + 1;
    }
 }

 void prnt(vector<int> v) {
     for (int i = 0; i < 20; i++) {
        cout << v[i] << "   ";
         if (i == 9 || i == 19) {
            cout << endl;
         }
     }
 }

 int main() {
     vector<int> vec1;
     vector<int> vec2;
     vec1.resize(200);
     vec2.resize(100);
     Vectors(vec1, vec2, 1, 3);
     prnt(vec1);
     prnt(vec2);
     return 0;
     system("pause");
 }

但是,当我运行它时,我得到的输出就是这个......

0     29046     -309340552     29046     32     0     134113   0   0   0   
-309339528     29046     64     0   48   0   0   0   986   169   
0   0   -309340552   29046   32   0   134113   0   0   0   
-309339528   29046   64   0   48   0   0   0   986   169 

另外,如果vec1和2未初始化为某种尺寸,它将不允许我使用Vectors方法。

我刚从Java转移到C ++,所以你能给我的任何帮助都会非常感激,因为在Java中被困在一些如此微不足道的东西是令人抓狂的

2 个答案:

答案 0 :(得分:3)

void Vectors(vector <int> v1, vector <int> v2, int s1, int s2) {

您按价值而不是参考传递向量,因此您需要更改副本,而不是原件。

相反,通过引用传递它们:

void Vectors(vector <int> & v1, vector <int> & v2, int s1, int s2) {

并且您将更改原始向量,并且您将在功能之外看到您的更改。

答案 1 :(得分:0)

您的输出似乎不正确!

Vectors应该将值设置为0. Visual Studio 2017就可以了,据我所知,这是标准的预期行为。

上述程序应打印4行,每行5个。

prnt除了自己制作副本并修改副本外没有任何影响(如前面的答案所述)。

但是,当您调用Vectors时,副本只会浪费一些效率,但您应该打印与main相同的值。然而,在不确保拥有它们的情况下打印20个数字并不是一个好主意。它使代码变得脆弱......因为必须确保添加了足够的项目。

话虽如此,你的reserve功能设计很糟糕。

  • 首先,这个名字毫无意义。
  • 其次,代码是重复的。因此,拥有一个可以从给定种子中随机化1个向量的函数会好得多。了解DRY原则。
  • 第三,它需要一份载体副本,主要是浪费时间。

一些旁注:

  • 正如某人所说,你也应该使用现代随机发生器。
  • 使用{{1}}或更新现有项目,而不是添加新项目。用200个零填充向量然后在末尾添加200个额外的随机数是没有意义的。