Вы можете использовать стандартный алгоритм std::adjacent_find
, чтобы найти пару элементов, для которых первый < второй, а затем поменять их местами.
Например
#include <iostream>
#include <algorithm>
#include <list>
#include <functional>
#include <iterator>
int main()
{
std::list<int> l = { 3, 2, 1, 2, 1, 3, 2 };
for (int x : l) std::cout << x << ' ';
std::cout << std::endl;
auto it = std::adjacent_find(l.begin(), l.end(), std::less<int>());
if (it != l.end()) std::swap(*it, *std::next(it));
for (int x : l) std::cout << x << ' ';
std::cout << std::endl;
}
Выход
3 2 1 2 1 3 2
3 2 2 1 1 3 2
Или, если вы хотите, чтобы обработать все такие ситуации, когда первый < второй, то вы можете использовать следующий код
#include <iostream>
#include <algorithm>
#include <list>
#include <functional>
#include <iterator>
int main()
{
std::list<int> l = { 3, 2, 1, 2, 1, 3, 2 };
for (int x : l) std::cout << x << ' ';
std::cout << std::endl;
std::list<int>::iterator it = l.begin();
while ((it = std::adjacent_find(it, l.end(), std::less<int>())) != l.end())
{
std::swap(*it, *std::next(it));
}
for (int x : l) std::cout << x << ' ';
std::cout << std::endl;
}
Выходной сигнал составляет
3 2 1 2 1 3 2
3 2 2 1 3 2 1
либо 'splice()' или 'std :: swap (* itr1, * itr2)' или 'erase()/insert()' – bobah
'std :: list' не очень удачный выбор для сортировки – LihO
good, но проблема также в том, что итератор на круге while. после 'swap' он будет указывать на элемент prev-prev. – abrahab