CS225: Data Structures and Programming Principles Homework 3
CS225: Data Structures and Programming Principles Homework 3
Engineering
Homework 3
1. Write a function Sum(v) that returns the sum of all elements in an STL vector v.
2. What is the output screen after the below C++ program has been executed.
#include <iostream>
#include <list>
using namespace std;
void main() {
list <int> L1,L2;
list <int>::iterator L1_Iter;
L1.push_front(5);
L1.push_back(10);
L1.push_front(8);
L1.push_back(2);
L1.pop_front();
L1.push_back(1);
L2.push_back( 10 );
L2.push_back( 20 );
Operation Output S
insertBefore(p2, 3)
insertFirst(9)
before(p3)
swapElements(p1, p2)
remove(p2)
first()
last()
isFirst(p2)
after(p3)
4. What is the output screen after the below C++ program has been executed.
#include <iostream>
#include <vector>
using namespace std;
vector<int> vec_gen(int n) {
vector<int> V;
for (int i=0; i< n; i++)
V.push_back(i*i);
return V;
}
void main() {
int S,i;
vector <int> Vect;
Vect = vec_gen(6);
S = Vect.size();
cout << "The Vect is:" << endl;
for (i=0; i<S; i++)
cout << Vect.at(i) << '\n';
getchar();
}
5. Write a C++ function to make a list of string which contains “Ha Noi”, “Ho Chi Minh”, “Da Nang”,
“Hai Phong”, “Can Tho”. Then, the function shows all these string to the output screen as below
Five largest cities in Vietnam are:
Ha Noi, Ho Chi Minh, Da Nang, Hai Phong, and Can Tho.
6. a. Write C++ code for the implementation of a database by using array as described below.
Array
Pointer0 Pointer1 Pointer2 Pointer3
b. Write a function to add a new student into the database at the position n
c. Write a function to remove a student from the database at the position n