Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

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 223 views
2 answers 71 views
2 answers 91 views
1 answer 134 views
1 answer 69 views
1 answer 79 views
3 answers 174 views
174 views asked Nov 20, 2022 by avibootz
...