Random Shuffling if List Items

I'm working with an STL list. Say that I have a list of 25 items, and I want to switch the value in the 10th element with the value in the 18th element. Anyone know how I would do this?

I've been looking at list::swap, but it looks like it swaps entire lists not individual elements within a single list.

Thanks.
closed account (DSLq5Di1)
Using std::iter_swap and std::advance achieves what you are after, but keep in mind that std::list does not allow random access, and finding the (n)th element requires walking through the list. Example below:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <algorithm>
#include <list>

template<class T>
inline void list_swap(std::list<T>& li, unsigned a, unsigned b)
{
	if (a && b && a != b && a <= li.size() && b <= li.size())
	{
		std::list<T>::iterator it_a, it_b = it_a = li.begin();

		std::advance(it_a, --a);
		std::advance(it_b, --b);

		std::iter_swap(it_a, it_b);
	}
}

int main()
{
	std::list<char> alpha(6);

	char ch = 'a';
	std::generate(alpha.begin(), alpha.end(), [&ch]() { return ch++; });

	std::for_each(alpha.begin(), alpha.end(), [](char x) { std::cout << x; });
	std::cout << std::endl;
	
	list_swap(alpha, 1, 6);
	list_swap(alpha, 4, 3);

	std::for_each(alpha.begin(), alpha.end(), [](char x) { std::cout << x; });
	
	std::cin.sync();
	std::cin.ignore();

	return 0;
}

abcdef
fbdcea

You may wish to pick a new container depending on your needs, see:-
http://linuxsoftware.co.nz/containerchoice.png
Thanks a lot. This worked really well. As for the tip about the container type, I agree, but this type is required with the assignment, so I have to use it.

Thanks again!
Topic archived. No new replies allowed.