Reputation: 11
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]);
Upvotes: 1
Views: 98
Reputation: 409364
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);
Upvotes: 5