It been awhile since I've used c++ as I have been using python more frequently however, I need a refresher on how to create a random number generator in vectors. The code currently keeps going as if it is a while loop due to the for loop. What I want is to create an empty vector with 5 slots and fill them in with 5 random numbers since I resized the vector to 5.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <cstdlib>
#include<vector>
usingnamespace std;
int main()
{
vector<int>vect;
vect.resize(5);
for (int i=0;i<vect.size();i++)
{
vect.push_back(rand()%10+1);
cout<<vect[i]<<endl;
}
}
> The code currently keeps going as if it is a while loop due to the for loop
I have no idea what you're trying to say
.resize() changes the size of the vector (in this case to 5)
.push_back() inserts an element to the end, so the size increases by 1
you may use brackets to access an element, `vect[3]' will access the fourth element of the vector
#include <iostream>
#include <vector>
#include <chrono>
#include <random>
int main()
{
// http://www.cplusplus.com/reference/random/mersenne_twister_engine/mersenne_twister_engine/unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::mt19937 generator( seed ); // mt19937 is a standard mersenne_twister_engine
// http://www.cplusplus.com/reference/random/uniform_int_distribution/
std::uniform_int_distribution<int> distribution(1, 10);
int N = 5; // size of vector does not need to be a compile-time constant
std::vector<int> V(N);
// ranged for syntax and automatically deduced type 'auto'
for ( auto& e : V ) e = distribution(generator);
for ( auto e : V ) std::cout << e << '\n';
}