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 188 views
188 views asked Feb 20, 2018 by avibootz
1 answer 79 views
79 views asked Nov 4, 2024 by avibootz
2 answers 171 views
171 views asked Nov 1, 2021 by avibootz
2 answers 207 views
1 answer 170 views
170 views asked Feb 20, 2018 by avibootz
1 answer 174 views
174 views asked Feb 19, 2018 by avibootz
2 answers 144 views
144 views asked Mar 25, 2023 by avibootz
...