Suppose we have a vector of integers declared as shown below
Suppose we have a vector of integers declared as shown below. For parts a-c of this problem, you are going to write some sections of code that will manipulate this vector.
vector <int> data;
Finish writing a section of code that will read integers from cin, until there are no more integers to read, and add the value which was read to the vector:
int input;
while ( cin >> input )
{
}
B). Write a call to the STL algorithm which will sort the vector. Do not write a sort function… just give the line or lines of code required to actually call the STL sort function:
C). List two of the three header files which will need to be included in order for all of the code in parts 3a and 3b to work:
D). Finish writing a recursive function called sum(), which will return the sum of the integers contained within the array passed to it (this has nothing to do with 3a-3c). Hint: if the size is 0, the function should return 0.
// Recursive function to sum an array
int sum( const int data[], int size )
{
}
Solution
// C++ code
 /*
 header files which will need to be included in order for all of the code in parts 3a and 3b to work
 #include <vector> and
 #include <algorithm> to sort vector
 #include <fstream> to open file
 */
#include <iostream>
 #include <fstream>
 #include <vector>
 #include <algorithm>
 using namespace std;
// Recursive function to sum an array
 int sum( const int data[], int size )
 {
     if(size == 0)
       return 0;
     else
       return data[size-1]+sum(data,size-1);
 }
int main ()
 {
 // vector
 vector <int> data;
// open file
 ifstream inputFile (\"input.txt\");
 if (inputFile.is_open())
 {
     int input;
     while ( inputFile >> input )
     {
         data.push_back(input);
     }   
     inputFile.close();
 }
 else cout << \"Unable to open file\";
cout << \"Unsorted vector: \";
 for (int i = 0; i < data.size(); ++i)
 {
     cout << data[i] << \" \";
 }
 cout << endl;
 cout << endl;
// call to the STL algorithm which will sort the vector
 sort(data.begin(), data.end());
cout << \"Sorted vector: \";
 for (int i = 0; i < data.size(); ++i)
 {
     cout << data[i] << \" \";
 }
 cout << endl;
 cout << endl;
int array[data.size()];
 for (int i = 0; i < data.size(); ++i)
 {
     array[i] = data[i];
 }
 int total = sum(array,data.size());
 cout << \"Sum: \" << total << endl;
return 0;
 }
/*
 input.txt
 7
 8
 5
 4
 3
 6
 8
 9
 1
 10
output:
 Unsorted vector: 7 8 5 4 3 6 8 9 1 10
 Sorted vector: 1 3 4 5 6 7 8 8 9 10
 Sum: 61
*/



