Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- #include <cassert>
- #define INPUT_FILE "input.txt"
- #define OUTPUT_FILE "output.txt"
- using namespace std;
- class Vector {
- private:
- int n;
- float* data;
- public:
- Vector() {
- n = 0;
- data = NULL;
- }
- Vector(int n) { allocate(n); }
- ~Vector() { clear(); }
- void allocate(int n) {
- this->n = n;
- data = new float[n];
- }
- void clear() {
- this->n = 0;
- delete data;
- }
- void read(string filename) {
- ifstream ifs(filename);
- assert(ifs && "File cannot open!!!");
- ifs >> *this;
- }
- float calcAvg() {
- float avg = 0.;
- for (int i = 0; i < n; i++)
- avg += data[i];
- assert(n && "n = 0!!!");
- return avg / n;
- }
- float calcMult() {
- bool flag = false;
- float mult = 1., avg = calcAvg();
- for (int i = 0; i < n; i++)
- if (data[i] > avg) {
- flag = true;
- mult *= data[i];
- }
- assert(flag && "There are no elements > avg!!!");
- return mult;
- }
- void write(string filename) {
- ofstream ofs(filename);
- assert(ofs && "File cannot create!!!");
- ofs << *this;
- }
- friend ifstream& operator >> (ifstream& ifs, Vector& x);
- friend ofstream& operator << (ofstream& ofs, Vector& x);
- friend istream& operator >> (istream& is, Vector& x);
- friend ostream& operator << (ostream& os, Vector& x);
- };
- ifstream& operator >> (ifstream& ifs, Vector& x) {
- ifs >> x.n;
- x.allocate(x.n);
- for (int i = 0; i < x.n; i++)
- ifs >> x.data[i];
- return ifs;
- }
- ofstream& operator << (ofstream& ofs, Vector& x) {
- ofs << "n = " << x.n << endl;
- if (x.n) {
- ofs << "data: ";
- for (int i = 0; i < x.n; i++)
- ofs << x.data[i] << " ";
- ofs << endl;
- }
- float avg = x.calcAvg();
- float mult = x.calcMult();
- ofs << "avg = " << avg << endl;
- ofs << "mult = " << mult << endl;
- return ofs;
- }
- ostream& operator << (ostream& os, Vector& x) {
- cout << "n = " << x.n << endl;
- if (x.n) {
- cout << "data: ";
- for (int i = 0; i < x.n; i++)
- cout << x.data[i] << " ";
- cout << endl;
- }
- float avg = x.calcAvg();
- float mult = x.calcMult();
- cout << "avg = " << avg << endl;
- cout << "mult = " << mult << endl;
- return os;
- }
- istream& operator >> (istream& is, Vector& x) {
- cin >> x.n;
- x.allocate(x.n);
- for (int i = 0; i < x.n; i++)
- cin >> x.data[i];
- return is;
- }
- int main() {
- Vector x;
- x.read(INPUT_FILE);
- x.write(OUTPUT_FILE);
- cout << x;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment