NETB161. Week 2. VECTORS AND ARRAYS II

1. Inserting and removing elements

A. Write a function
void insert_element(vector<int>, int)
that inserts an element in a vector of integers. Suppose that the elements are sorted in increasing order and the new element must be inserted in such a way that the vector be sorted again. Test the function with a vector, whose elements are stored in a file (using input redirection).

REMEMBER:

To insert an element in the middle of a vector, you must add a new element at the end of the vector and move all elements above the insertion location up by one slot.

void insert(vector<string>& v, int pos, string s)
{ int last = v.size()-1;
v.push_back(v[last]);
for (int i = last; i > pos; i--) v[i] = v[i-1];
v[pos] = s;
}

To link a file to the input of a program words, you type

words < article.txt
on a command line. The input instructions no longer expect input from the keyboard but from the file article.txt.

B. Write a function
void erase_first(vector<int>)
that removes the fist element of an integer vector, not changing the order of the remaining elements.

REMEMBER:

You must move all elements down by one slot, then shrink the size of the vector.

void erase(vector<string>& v, int pos)
{ for (int i = pos; i < v.size()-1; i++) v[i] = v[i+1];
v.pop_back();
}
Read a vector from a file, remove it's first element, and save the elements to another file (using input and output redirection).
    program <input.txt >output.txt

2. Character arrays

Write a program, that reads an natural number as a string, then convert it to a floating point number and output it's square root. Use the member-function c_str and atoi function.

REMEMBER: