Solved

# IMplementation

Posted on 2006-04-17

Implement the “empty” functions in this program. The functions requirements are as follows:

• alternating_sum function computes the alternating sum of all elements in a vector. For example, if alternating_sum is called with a vector containing {1 4 9 16 9 7 4 9 11} then it computes 1-4+9-16+9-7+4-9+11 = -2.

• append function appends one vector after another. For example if a is {1 4 9 16} and b is {9 7 4 9 11} the append(a,b) returns the vector {1 4 9 16 9 7 4 9 11}

• same_set function checks whether two vectors have the same elements in some order, ignoring multiplicities. For example two vectors a {1 4 9 16 9 7 4 9 11} and b {11 11 7 9 16 4 1} would be considered identical, thus same_set(a,b) returns true. You will probably need one or more “helper” functions.

• remove_duplicates function removes duplicates from a vector. For example, if it is called with a vector {1 4 9 16 9 7 4 9 11}, then the vector is changed to {1 4 9 16 7 11}

The skeleton code also contains a driver for these functions. If you implement the functions correctly, your program should print the following result:

The alternating sum of vector a is: -2

The elements of the vectors a and b form the same set.

Appending a after b generates a new vector that contains the following data:

11 11 7 9 16 4 1 1 4 9 16 9 7 4 9 11

The vector a without duplicates contains the following data:

1 4 9 16 7 11

#include <iostream>

#include <vector>

using namespace std;

/*

Functions on Vectors.

*/

//computes the alternating sum of all elements in a vector

int alternating_sum(vector<int> a)

{

}

//appends vector b after a.

vector<int> append(vector<int> a, vector<int> b)

{

}

//checks whether two vectors have the same elements,

//ignoring multiplicities

bool same_set(vector<int>a, vector<int> b)

{

}

//removes duplicates from a vector

void remove_duplicates(vector<int>& a)

{

}

void display_vector( string vector_name, vector<int> a)

{

cout << vector_name << " contains the following data: \n";

for (int i=0; i<a.size(); i++)

cout<< a[i] << " ";

cout<<"\n\n";

}

int main()

{

vector<int> a(9);

vector<int> b(7);

a[0] = 1;

a[1] = 4;

a[2] = 9;

a[3] = 16;

a[4] = 9;

a[5] = 7;

a[6] = 4;

a[7] = 9;

a[8] = 11;

b[0] = 11;

b[1] = 11;

b[2] = 7;

b[3] = 9;

b[4] = 16;

b[5] = 4;

b[6] = 1;

// test "alternating_sum" function:

cout << "The alternating sum of vector a is: ";

cout << alternating_sum (a) << "\n\n";

//test "same_set" function

cout << "The elements of the vectors a and b form ";

if (!same_set(a, b)) cout << "not ";

cout << "the same set.\n\n";

//test "append" function:

display_vector ("Appending a after b generates a new vector that", append(b, a) );

//test "remove duplicates" function:

remove_duplicates(a);

display_vector ("The vector a without duplicates", a );

return 0;

}