Swap neighbouring elements in std::list

c++, containers, sorting, stl

Solution

You can easily do this by using two iterators:

void biswap(std::list<int> &l)
{
    if (l.size() < 2)
        return;
    auto it2 = l.begin();
    auto it1 = it2++;
    auto e = l.end();
    for (;;)
    {
        if (*it1 < *it2)
            std::swap(*it1, *it2);
        it1 = it2++;
        if (it2 == e)
            return;
        it1 = it2++;
        if (it2 == e)
            return;
    }
}

Live example

Note: in case you're not using C++11 and thus calling `size()` might present a significant overhead, you can replace it with this (and of course replace all usage of `auto` with explicit types):

void biswap(std::list<int> &l)
{
    auto it2 = l.begin();
    auto e = l.end();
    if (it2 == e)
        return;
    auto it1 = it2++;
    if (it2 == e)
        return;
    for (;;)
    // ... the rest as before
}

Problem

I want to change places of neighbouring elements in the `std::list` Example of the list and values ``` A B C D E F G 3 2 1 2 1 3 2 ``` What I expect to receive after sorting: ``` A B D C F E G 3 2 2 1 3 1 2 ``` So, simple `A > B` = nothing to do, but `C < D` = swap them and go to `E` comparison. I have no idea about how to swap neighbor elements. So, I want to move forward to 1 step `good` elements

Original source