【问题标题】:Trying to sort list of numbers in c++尝试在 C++ 中对数字列表进行排序
【发布时间】:2020-06-04 11:39:45
【问题描述】:

我正在尝试通过将填充了随机值的用户设置长度列表传递给将按升序对元素进行排序的函数来对数字列表进行排序。

我在使用数组之前已经解决了这个问题并且没有问题。出于某种原因,我的代码无法正常工作,如果你们能帮助我找出它无法正常工作的原因,我将不胜感激。它将对数字进行排序,但最后一个数字将未排序。

函数如下:

void sort(std::list<int>& numbers)
{
    list<int>::iterator it;
    list<int>::iterator it2;
    for (it = numbers.begin(); it != numbers.end(); ++it)
    {
        for (it2 = ++numbers.begin(); it2 != numbers.end(); ++it2)
        {
            if (*it > *it2)
            {
                int temp = *it;
                *it = *it2;
                *it2 = temp;
            }
        }
    }
}

【问题讨论】:

  • 除非它是实现您自己的排序的任务的一部分,否则使用std::sort(或者在std::list的情况下,std::list::sort)。
  • 你试过调试这个吗?

标签: c++ list sorting


【解决方案1】:

您的算法不起作用,因为第二个周期总是一次又一次地遍历(几乎)整个列表。它应该做的,只是通过剩余的部分。 IE。第二个周期应该是:

for (it2 = std::next(it1); it2 != numbers.end(); ++it2)

另外,由于第二个循环从“下一个”元素开始,第一个循环不应该到最后一个元素,而是到倒数第二个元素。 IE。像这样:

for (it = numbers.begin(); it != std::prev(numbers.end()); ++it)

但是,由于std::prev() 只为双向迭代器定义,而std::list 没有提供,它可能更容易重写为:

for (it = numbers.begin(); std::next(it) != numbers.end(); ++it)

【讨论】:

  • 谢谢,剪切和粘贴“for (it2 = std::next(it1); it2 != numbers.end(); ++it2)” 有效。我刚刚了解了迭代器,所以我认为 '++' 可以解决问题。
猜你喜欢
  • 1970-01-01
  • 2013-07-30
  • 2015-08-17
  • 1970-01-01
  • 2021-02-01
  • 1970-01-01
  • 2017-10-28
  • 1970-01-01
相关资源
最近更新 更多