STL sort failure

Could someone please tell me why the STL sort method in this program aborts the program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <list>
#include <algorithm>

int main()
{
	using namespace std;
	
	srand(time(NULL));
	int vector_size;
	
	cout << "How many numbers would you like for this test? ";
	cin >> vector_size;
	
	vector<int> vi0, vi;
	list<int> li;
	
	for (int i = 0; i < vector_size; i++)
		vi0.push_back(rand() % 100 + 1);
	
	vi = vi0;
	copy(vi0.begin(), vi0.end(), li.begin());
	
	clock_t start = clock();
	sort(vi.begin(), vi.end());
	clock_t end = clock();
	cout << "vi0 sort time: " << (double)(end - start)/CLOCKS_PER_SEC << endl;

	start = clock();
	li.sort();
	end = clock();
	cout << "li sort time: " << (double)(end - start)/CLOCKS_PER_SEC << endl;
	
	return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
        // ...
	vector<int> vi0, vi;
	list<int> li;
	
	for (int i = 0; i < vector_size; i++)
		vi0.push_back(rand() % 100 + 1);
	
	vi = vi0;

	// *** error; list li is empty; leads to undefined behaviour
	copy(vi0.begin(), vi0.end(), li.begin());  // *** 
       // ...
       // undefined behaviour 

Thank you, I'm sorry for the newbie question. I've substituted it with this now but if anyone can tell me if there is a more efficient way of coding this it would be greatly appreciated.

1
2
for (int i = 0; i < vector_size; i++)
		li.push_back(vi0[i]); 
Slightlty more efficient:
1
2
3
4
vector<int> vi0, vi;
list<int> li;
// push_back etc ...
li.assign( vi0.begin(), vi0.end() ) ;


Or better, don't define li till we know how to initialize it:
1
2
3
vector<int> vi0, vi;
// push_back etc ...
list<int>li( vi0.begin(), vi0.end() ) ;


Once again thank you for the help. Unfortunately I wasn't aware/overlooked the fact you can initialize those containers through iterator ranges.
Topic archived. No new replies allowed.