vector
#include#include #include using namespace std;// 函数声明 void output1(vector &); void output2(vector &); int main(){ vector likes, dislikes; // 创建vector 对象likes和dislikes // 为vector 数组对象likes添加元素值 ( favorite book, music, film, paintings,anime,sport,sportsman,etc) // 补足代码 // 。。。 likes.push_back("favorite book, music, film, paintings,anime,sport,sportsman,etc"); cout << "-----I like these-----" << endl; // 调用子函数输出vector 数组对象likes的元素值 // 补足代码 // 。。。 output2(likes); // 为vector 数组对象dislikes添加元素值 // 补足代码 // 。。。 dislikes.push_back("没有"); cout << "-----I dislike these-----" << endl; // 调用子函数输出vector 数组对象dislikes的元素值 // 补足代码 // 。。。 output1(dislikes); // 交换vector 对象likes和dislikes的元素值 // 补足代码 // 。。。 likes.swap(dislikes); cout << "-----I likes these-----" << endl; // 调用子函数输出vector 数组对象likes的元素值 // 补足代码 // 。。。 output1(likes); cout << "-----I dislikes these-----" << endl; // 调用子函数输出vector 数组对象dislikes的元素值 // 补足代码 // 。。。 output2(dislikes); return 0;}
6-17
1 #include2 using namespace std;3 int main(){4 int *p;5 *p=9;// 改正:int m=5; p=&m;6 cout <<"The value at p:"<<*p;7 return 0;8 }
6-18
#includeusing namespace std;int fn1() //int *fn1() { int *p=new int (5); return *p; //return p;}int main(){ int a=fn1(); //int *a=fn1(); cout<<"the value of a is:"<
matrix
1 //main 2 #include3 using namespace std; 4 #include"matrix.h" 5 /* run this program using the console pauser or add your own getch, system("pause") or input loop */ 6 7 int main(int argc, char** argv) { 8 Matrix a(3); 9 float s[3][3]={ 1,2,3,4,5,6,7,8,9};10 const float *p;11 p=s[0];12 a.setMatrix(p);13 a.printMatrix();14 cout< <
1 #ifndef MATRIX_H 2 #define MATRIX_H 3 class Matrix { 4 public: 5 Matrix(int n); // 构造函数,构造一个n*n的矩阵 6 Matrix(int n, int m); // 构造函数,构造一个n*m的矩阵 7 Matrix(const Matrix &X); // 复制构造函数,使用已有的矩阵X构造 8 ~Matrix(); //析构函数 9 void setMatrix(const float *pvalue); // 矩阵赋初值,用pvalue指向的内存块数据为矩阵赋值 10 void printMatrix() const; // 显示矩阵11 inline float &element(int i, int j){12 return *(p+i*cols+j);13 } //返回矩阵第i行第j列元素的引用14 inline float element(int i, int j) const;// 返回矩阵第i行第j列元素的值 15 void setElement(int i, int j, int value); //设置矩阵第i行第j列元素值为value16 inline int getLines() const{17 return lines;18 } //返回矩阵行数 19 inline int getCols() const{20 return cols;21 }22 //返回矩阵列数 23 private:24 int lines; // 矩阵行数25 int cols; // 矩阵列数 26 float *p; // 指向存放矩阵数据的内存块的首地址 27 };28 29 #endif
1 #include"matrix.h" 2 #include3 using namespace std; 4 Matrix::Matrix(int n):lines(n),cols(n){ 5 } 6 Matrix::Matrix(int n,int m):lines(n),cols(m){ 7 } 8 Matrix::Matrix(const Matrix &X){ 9 lines=X.lines;10 cols=X.cols;11 p=X.p;12 }13 void Matrix::setMatrix(const float *pvalue){14 p=(float*)pvalue;15 }16 void Matrix::printMatrix() const{17 int i,j;18 for(i=0;i