How to shuffle a list in C++

1 Answer

0 votes
#include <iostream>
#include <list>
#include <vector>
#include <random>
#include <algorithm>
#include <chrono>

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

int main()
{
	std::list<int> lst;
	std::mt19937 gen(std::chrono::system_clock::now().time_since_epoch().count());

	for (int i = 0; i < 10; i++)
		lst.push_back(i);

	std::vector<int> vec(lst.begin(), lst.end());
	std::shuffle(vec.begin(), vec.end(), gen);
	lst.assign(vec.begin(), vec.end());

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

	cout << endl;

	return 0;
}


/*
run:

2 6 7 3 1 4 8 0 5 9

*/

 



answered Feb 19, 2018 by avibootz

Related questions

1 answer 274 views
274 views asked Feb 20, 2018 by avibootz
1 answer 153 views
153 views asked Nov 4, 2024 by avibootz
2 answers 292 views
292 views asked Nov 1, 2021 by avibootz
2 answers 325 views
1 answer 260 views
260 views asked Feb 20, 2018 by avibootz
1 answer 280 views
280 views asked Feb 19, 2018 by avibootz
2 answers 257 views
257 views asked Mar 25, 2023 by avibootz
...