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 the first element, and save the elements to another file.
{ for (int i = pos; i < v.size()-1; i++) v[i] = v[i+1];
v.pop_back();
}
2. Parallel vectors
Look at the program and explain its purpose. Write down the code, compile and start the program.#include<cstdlib>
#include<vector>
using namespace std;
#include "ccc_win.h"
class Cloud {
public:
Cloud();
void add_point(Point p);
void plot() const;
private:
vector<Point> dots;
};
void rand_seed()
{ int seed = static_cast<int>(time(0));
srand(seed);
}
double rand_double(double a, double b)
{ return a + (b - a) * rand() * (1.0 / RAND_MAX); }
Cloud::Cloud(){}
void Cloud::add_point(Point p)
{ dots.push_back(p); }
void Cloud::plot() const
{ int i;
for (i = 0; i < dots.size(); i++) cwin << dots[i];
}
int main()
{ rand_seed();
Cloud random_cloud;
int i;
for (i = 1; i <= 100; i++)
random_cloud.add_point(Point(rand_double(-4, 4),
rand_double(-4, 4)));
random_cloud.plot();
return 0;
}
3. Character arrays
4. Two-dimensional arrays
Syntax 9.4 : Two-Dimensional Array Definition
type_name variable_name[size1][size2];
|
void print_table(const double table[][BALANCES_COLS], int table_rows)
{ const int WIDTH = 10;
cout << setiosflags(ios::fixed) << setprecision(2);
for (int i = 0; i < table_rows; i++)
{ for (int j = 0; j < BALANCES_COLS; j++)
cout << setw(WIDTH) << table[i][j];
cout << "\n";
}
}
double future_value(double initial_balance, double p, int n)
{ double b = initial_balance * pow(1 + p / 100, n);
return b;
}