用向量填充随机数c ++ [英] Fill a vector with random numbers c++
问题描述
我有一个向量,我试图填补随机数字。我继续遇到一个问题,但是矢量大多数输出0每次我运行它(它不应该输出0)。我在下面写的代码中做错了,使其输出0(它比任何其他数字输出0更多):
vector< int> myVector;
srand((unsigned)time(NULL));
int a = rand()%20 + 1; // 1到20
for(int i = 0; i int b = rand()%20 + 1;
myVector.push_back(b);
cout<< myVector [b]<< endl;
}
我是一个初学者,没有做太多的C ++编程我不知道是什么使我的代码故障。
您在向量中调用错误的索引
尝试:
cout< myVector [i]< endl;
否则你将冒险跑掉顶点的前20个迭代。 p>
您也可以致电 .back()在您的向量上获得向量中的最后一项。
I've got a vector that I'm trying to fill up with random numbers. I keep running into an issue however that the vector mostly outputs 0 each time that I'm running it (it shouldn't output a 0 ever). What am I doing wrong in my code written below to make it output 0 (it outputs 0 more so than any other number):
vector<int> myVector;
srand((unsigned)time(NULL));
int a = rand() % 20 + 1; //1 to 20
for (int i =0; i < a; i++){
int b = rand() % 20 + 1;
myVector.push_back(b);
cout << myVector[b] << endl;
}
I am a beginner and have not done much C++ programming in a long time so I'm not sure what is making my code malfunction. If someone could explain what I've done wrong it would be greatly appreciated.
You are calling the wrong index in your vector
Try doing:
cout << myVector[i] << endl;
else you will risk running off the end of your vertex for the first 20 or so iterations.
You can also call .back() on your vector to get the last item in the vector.
这篇关于用向量填充随机数c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!