'How to call swap() algorithm on std::list elements?

I'm trying to swap the 2nd and 4th elements in a list, but I can't figure out how to do this. I tried to use vector notation, but it didn't work.

list<int> a1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
swap(a1[1], a1[3]);


Solution 1:[1]

A std::list doesn't provide random access indexing, like a std::vector or an array does. You need to use iterators instead, eg:

auto first_node = a1.begin();
auto second_node = std::next(first_node);
auto fourth_node = std::next(first_node, 3);

std::swap(*second_node, *fourth_node);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Remy Lebeau