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]);
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);
It should be noted that due to the lack of random access, calling std::next(...) will iterate over the list to get to the correct node. Thus it is O(n).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With