我对C 中共享指针列表进行排序的功能未完成类型

my function to sort a shared pointer list in c++ is not completing the sort

本文关键字:排序 功能 未完成 类型 共享 指针 列表 我对      更新时间:2023-10-16

我有一个共享指针的stl std::list,指向节点对象,需要用它们各自的 id数字进行排序。

do
{
    check = 0, i = 0;
    auto it = newList.begin();
    while (i < newList.size() - 1)
    {
        first = *it;
        second = *++it;
        if (comp_id(first, second))
        {
            temp = second;
            second = first;
            first = temp;
            check = 1;
        }
        i++;
    }
} while (check == 1);

在此代码中,comp_id()返回true,并通过组织运行,但是在list发生时,没有任何变化。我希望对为什么会发生这种情况以及如何修复它有一些观点。

P.S。我不允许使用list_name.sort()方法:(

它不起作用的原因是因为您仅对列表中的 copies 进行修改(firstsecond(。您根本没有修改列表的实际内容。

要使代码工作,只需将您的 firstsecond变量更改为列表迭代器,然后在要访问其值时将它们更改为listerference,例如:

auto size = newList.size();
if (size > 1)
{
    --size;
    do
    {
        check = 0, i = 0;
        auto it = newList.begin();
        while (i < size)
        {
            auto first = it;
            auto second = ++it;
            if (comp_id(*first, *second))
            {
                auto temp = *second;
                *second = *first;
                *first = temp;
                check = 1;
            }
            ++i;
        }
    }
    while (check == 1);
}

为此,i也可以用迭代器代替:

if (newList.size() > 1)
{
    auto begin = newList.begin();
    auto end = newList.end()-1;
    do
    {
        check = 0;
        auto it = begin;
        while (it != end)
        {
            auto first = it;
            auto second = ++it;
            if (comp_id(*first, *second))
            {
                auto temp = *second;
                *second = *first;
                *first = temp;
                check = 1;
            }
        }
    }
    while (check == 1);
}