将数字有序地插入到链表中

时间:2017-12-03 02:05:27

标签: c++

我生成一系列随机数并将它们推回到矢量中。然后我想逐个将它们有序地插入到链表中并打印列表。但总是会抛出错误。

#include"std_lib_facilities.h"
#include <chrono>

#define N 100
int random_numbers()
{
    random_device rd;  //Will be used to obtain a seed for the random number engine
    mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
    uniform_int_distribution<> dis(0, N);
    int a = 0;
    a = dis(gen);
    return  a;
}

vector<int> randoms;
void get_random_numbers()
{
    for (int i = 0; i < N; i++)
    {
        randoms.push_back(random_numbers());
    }
}


void insert_in_lists()
{

    list<int> l ;
    for (int i = 0; i < N; i++)
    {
        list<int>::iterator it = l.begin();
        if (i = 0)
        {
            l.insert(it, randoms[i]);
        }
        else 
        {
            for (list<int>::iterator p = l.begin(); p != l.end(); p++)
            {

                if (randoms[i]<= *p)
                {
                    it = p;
                    //break;
                }
            }
            l.insert(it, randoms[i]);
        }       
    }
    for (list<int>::iterator p = l.begin(); p != l.end(); p++)
    {

        cout << *p << endl;
    }
}

int main()
{
    get_random_numbers()
    insert_in_lists();


    keep_window_open();
    return 0;
}

我想得到一系列排序的数字,如: 1 2 2 2 3 4 5 6 6 6 6 6 7 ....... 错误:Problem06.exe中0x74F608B2处的未处理异常:Microsoft C ++异常:内存位置0x00EFF884处的Range_error。

1 个答案:

答案 0 :(得分:1)

这简单得多:

{{1}}

这样,我们有效地构造和排序向量,然后将其值复制到列表中。这将更快,代码更简单。