将一个数字有序地插入链表

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

#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;

}

我想获得像一系列有序号码的:在Problem06未处理的异常在0x74F608B2: 1 2 2 2 3 4 5 6 6 6 6 6 7 ....... ERROR .exe:Microsoft C++异常:内存位置0x00EFF884的Range_error。

回答:

它是如此简单得多:

#define N 100 

vector<int> get_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);

vector<int> randoms(N);

for (int i = 0; i < N; i++)

{

randoms[i] = dis(gen);

}

return randoms;

}

void insert_in_lists()

{

vector<int> randoms = get_random_numbers();

sort(randoms.begin(), randoms.end());

list<int> l(randoms.begin(), randoms.end());

for (list<int>::iterator p = l.begin(); p != l.end(); p++)

{

cout << *p << endl;

}

}

这样,我们有效地构造和排序的载体,那么它的值复制到列表中。这将更快,代码更简单。

以上是 将一个数字有序地插入链表 的全部内容, 来源链接: utcz.com/qa/259197.html

回到顶部