How to randomly shuffle a list in C++

1 Answer

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

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

int main()
{
	std::list<int> lst;
	
	std::srand(std::time(0));

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

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

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

	cout << endl;

	return 0;
}


/*
run:

3 7 2 5 9 1 4 0 8 6

*/

 



answered Feb 20, 2018 by avibootz

Related questions

1 answer 279 views
279 views asked Feb 19, 2018 by avibootz
2 answers 289 views
289 views asked Nov 8, 2023 by avibootz
1 answer 257 views
257 views asked Feb 19, 2018 by avibootz
2 answers 319 views
1 answer 152 views
152 views asked Nov 4, 2024 by avibootz
2 answers 291 views
291 views asked Nov 1, 2021 by avibootz
...