task 5:
#include<iostream> #include <cassert> #include<stdlib.h> #define value 1 using namespace std; class vectorint { public: vectorint(int a) { elem=new int[a]; size=a; cout<<"gouzao1"<<endl; } vectorint(int a,int b) { elem=new int[a]; size=a; for(int i=0;i<a;i++) elem[i]=value; cout<<"gouzao2"<<endl;} vectorint(const vectorint &v) { size=v.size; elem=new int[v.size]; for(int i=0;i<v.size;i++) elem[i]=v.elem[i]; cout<<"gouzao3"<<endl; } ~vectorint() { delete[] elem; cout<<"xigou"<<endl; } int getsize(){return size;} int &at(int a) { assert(a >= 0 && a < size); return elem[a]; } friend void output(vectorint &v) { for(int i=0;i<v.size;i++) cout<<v.elem[i]<<" "; cout<<endl; } private: int *elem; int size; };
#include <iostream> #include "vectorint.hpp" #define vectorInt vectorint void test() { using namespace std; int n; cin >> n; vectorInt x1(n); for(auto i = 0; i < n; ++i) x1.at(i) = i*i; output(x1); vectorInt x2(n, 42); vectorInt x3(x2); output(x2); output(x3); x2.at(0) = 77; output(x2); output(x3); } int main() { test(); }
截图:
task6:
#include<iostream> #include <cassert> #pragma once #include<stdlib.h> #define x lines #define y cols using namespace std; class Matrix { public: Matrix(int n):x(n),y(n){p=new double[n*n];} // 构造函数,构造一个n*n的矩阵 Matrix(int n, int m):x(n),y(m){p=new double[n*m];} // 构造函数,构造一个n*m的矩阵 Matrix(const Matrix &X):x(X.x),y(X.y) { p=new double[x*y]; for(int i=0;i<x*y;i++) p[i]=X.p[i]; } // 复制构造函数,使用已有的矩阵X构造 ~Matrix(){delete[] p;} //析构函数 void set(const double *pvalue) { for(int i=0;i<x*y;i++) p[i]=pvalue[i]; } // 用pvalue指向的连续内存块数据按行为矩阵赋值 void set(int i, int j, int value){p[i*y+j]=value;} //设置矩阵第i行第j列元素值为value double &at(int i, int j) { assert( i>= 0 && i < x && j>=0 && j<y); return p[i*y+j]; } //返回矩阵第i行第j列元素的引用 double at(int i, int j) const{return p[i*y+j]; } // 返回矩阵第i行第j列元素的值 int get_lines() const{return x;} //返回矩阵行数 int get_cols() const{return y;} //返回矩列数 void print() const { int k=0; for(int i=0;i<x*y;i++) { cout<<p[i]<<" "; k++; if(k==y) { cout<<endl; k=0; } } } // 按行打印输出矩阵 private: int lines; // 矩阵行数 int cols; // 矩阵列数 double *p; // 指向存放矩阵数据的内存块的首地址 }; // 类Matrix的实现:待补足 // ×××
#include <iostream> #include "matrix.hpp" void test() { using namespace std; double x[] = {1, 2, 3, 4, 5, 6}; Matrix m1(3, 2); // 创建一个3×2的矩阵 m1.set(x); // 用一维数组x的值按行为矩阵m1赋值 m1.print(); // 打印矩阵m1的值 cout << "the first line is: " << endl; cout << m1.at(0, 0) << " " << m1.at(0, 1) << endl; // 输出矩阵m1第1行两个元素的值 cout << endl; Matrix m2(2, 3); m2.set(x); m2.print(); cout << "the first line is: " << endl; cout << m2.at(0, 0) << " " << m2.at(0, 1) << " " << m2.at(0, 2) << endl; cout << endl; Matrix m3(m2); // 用矩阵m2构造新的矩阵m3 m3.set(0, 0, 999); // 将矩阵m3第0行第0列元素值设为999 m3.print(); } int main() { test(); }
截图:
标签:Matrix,m1,int,实验,x2,output,include From: https://www.cnblogs.com/202183290359gyk/p/16872381.html