How to fill a vector with random numbers in C++

2 Answers

0 votes
#include <iostream>
#include <vector>
#include <ctime>

using std::cout;
using std::endl;

int main()
{
	std::vector<int> vec(5);

	srand((unsigned)time(NULL));
  
	for (int i = 0; i < 5; i++) 
		vec[i] = rand() % 100 + 1;

	for (auto i : vec) {
		cout << i << " ";
	}

	cout << endl;

	return 0;
}


/*
run:

13 63 33 51 66

*/

 



answered Feb 18, 2018 by avibootz
0 votes
#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
#include <functional>

using std::cout;
using std::endl;

int main()
{
	std::vector<int> vec(5);

	std::random_device rd;
	std::mt19937 mt(rd());
	std::uniform_int_distribution<int> uid(1, 100);

	auto gen = std::bind(uid, mt);

	generate(begin(vec), end(vec), gen);

	for (auto i : vec) {
		cout << i << " ";
	}

	cout << endl;

	return 0;
}


/*
run:

52 99 3 91 88

*/

 



answered Feb 18, 2018 by avibootz
edited Feb 19, 2018 by avibootz

Related questions

1 answer 245 views
2 answers 100 views
2 answers 110 views
1 answer 163 views
1 answer 92 views
1 answer 93 views
3 answers 199 views
199 views asked Nov 20, 2022 by avibootz
...