Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

algorithm

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]);
like image 922
YUreee Avatar asked Jun 09 '26 14:06

YUreee


1 Answers

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).

like image 130
Some programmer dude Avatar answered Jun 11 '26 08:06

Some programmer dude