1. Inserting and removing elements
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).void insert_element(vector<int>, int)
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
on a command line. The input instructions no longer expect input from the keyboard but from the file article.txt.words < article.txt
that removes the fist element of an integer vector, not changing the order of the remaining elements.void erase_first(vector<int>)
void erase(vector<string>& v, int pos)Read a vector from a file, remove it's first element, and save the elements to another file (using input and output redirection).
{ for (int i = pos; i < v.size()-1; i++) v[i] = v[i+1];
v.pop_back();
}
program <input.txt >output.txt
2. Character arrays
int atoi(const char s[])
string year = "1999";
int y = atoi(year.c_str());