Assertion failure

My adjacent_difference function is causing my program to crash. What am I doing wrong?

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
39
40
41
//C++ Programming 141 - STL misc functions
#include <iostream>
#include <algorithm>
#include <numeric>
#include <iterator>
#include <vector>
#include <functional>

using namespace std;

void print(vector<int>);

int main()
{
	int list[8] = {1,2,3,4,5,6,7,8};
	vector<int> vecList(list, list + 8);
	vector<int> newList;

	cout << "vecList = ";
	print(vecList);

	int sum = accumulate(vecList.begin(), vecList.end(), 0);
	cout << "sum elements of vecList = " << sum << endl;

	int product = accumulate(vecList.begin(), vecList.end(), 1, multiplies<int>());
	cout << "product elements of vecList = " << product << endl;

	adjacent_difference(vecList.begin(), vecList.end(), newList.begin());
	cout << "newList = ";
	print(newList);
	system("PAUSE");
	return 0;
}

void print(vector<int> list)
{
	ostream_iterator<int> out(cout, " ");

	copy(list.begin(), list.end(), out);
	cout << endl;
}
What is the problem? You should observe the state of the program when the assertion failure occurs so you can debug it.
closed account (2UD8vCM9)
Reason your code is breaking is because you're trying to input values into a vector that has a size of 0. You first need to resize your newList vector for it to work. revised code below. Only added one line of code.

The code resizes newList to be the same size as vecList.

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
39
40
41
//C++ Programming 141 - STL misc functions
#include <iostream>
#include <algorithm>
#include <numeric>
#include <iterator>
#include <vector>
#include <functional>

using namespace std;

void print(vector<int>);

int main()
{
	int list[8] = {1,2,3,4,5,6,7,8};
	vector<int> vecList(list, list + 8);
	vector<int> newList;

	cout << "vecList = ";
	print(vecList);

	int sum = accumulate(vecList.begin(), vecList.end(), 0);
	cout << "sum elements of vecList = " << sum << endl;

	int product = accumulate(vecList.begin(), vecList.end(), 1, multiplies<int>());
	cout << "product elements of vecList = " << product << endl;
	newList.resize(vecList.size());
	adjacent_difference(vecList.begin(), vecList.end(), newList.begin());
	cout << "newList = ";
	print(newList);
	system("PAUSE");
	return 0;
}

void print(vector<int> list)
{
	ostream_iterator<int> out(cout, " ");

	copy(list.begin(), list.end(), out);
	cout << endl;
}
Last edited on
Thank you for the replies, I had newList(8) in the declaration but was outputting all 1's and I thought it was wrong.
Topic archived. No new replies allowed.