我在 C++ 中对共享指针列表进行排序的函数没有完成排序
my function to sort a shared pointer list in c++ is not completing the sort
我有一个包含 5 个共享指针的 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()
returns 为真,并贯穿整个组织,但 list
发生时没有任何变化。我希望对发生这种情况的原因以及如何解决它有一些看法。
P.S。我不允许使用 list_name.sort()
方法 :(
它不起作用的原因是因为您仅对局部变量(first
和 second
)进行修改,它们是值的 副本 从列表中。您根本没有修改列表的实际内容。
要使代码正常工作,只需将 first
和 second
变量更改为列表迭代器,然后在您想访问它们的值时取消引用它们,例如:
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);
}
我有一个包含 5 个共享指针的 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()
returns 为真,并贯穿整个组织,但 list
发生时没有任何变化。我希望对发生这种情况的原因以及如何解决它有一些看法。
P.S。我不允许使用 list_name.sort()
方法 :(
它不起作用的原因是因为您仅对局部变量(first
和 second
)进行修改,它们是值的 副本 从列表中。您根本没有修改列表的实际内容。
要使代码正常工作,只需将 first
和 second
变量更改为列表迭代器,然后在您想访问它们的值时取消引用它们,例如:
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);
}