1.#include <iostream>
#include <vector>
#include <string>
using namespace std;
void output1(vector<string> &);
void output2(vector<string> &);
int main()
{
vector<string>likes, dislikes;
paintings,anime,sport,sportsman,etc)
likes.push_back("favorite book");
likes.push_back("music");
likes.push_back("film");
likes.push_back("paintings");
cout << "-----I like these-----" << endl;
output1(likes);
dislikes.push_back("anime");
dislikes.push_back("sport");
dislikes.push_back("sportsman");
cout << "-----I dislike these-----" << endl;
output2(dislikes) ;
likes.swap(dislikes);
cout << "-----I likes these-----" << endl;
output2(likes);
cout << "-----I dislikes these-----" << endl;
output1(dislikes);
return 0;
}
void output1(vector<string> &v) {
int i;
for(i=0;i<v.size();i++)
cout<<v[i]<<endl;
}
void output2(vector<string> &v) {
vector<string>::iterator it;
for(it=v.begin();it!=v.end();it++)
cout<<*it<<endl;
}
6-17
#include<iostream>
using namespace std;
int main(){
int *p;
*p=9;
cout <<"The value at p:"<<*p;
return 0;
}
6-18
#include<iostream>
using namespace std;
int fn1()
{
int *p=new int (5);
return *p;
}
int main(){
int a=fn1();
cout<<"the value of a is:"<<a;
return 0;
}
matrix
#include <iostream>
using namespace std;
#include"matrix.h"
int main(int argc, char** argv) {
Matrix a(3);
float s[3][3]={1,2,3,4,5,6,7,8,9};
const float *p;
p=s[0];
a.setMatrix(p);
a.printMatrix();
cout<<a.element(0,0)<<endl;
cout<<a.getCols()<<endl;
cout<<a.getLines()<<endl;
a.setElement(0,0,0);
a.printMatrix();
return 0;
}
#endif
#ifndef MATRIX_H
#define MATRIX_H
class Matrix {
public:
Matrix(int n);
Matrix(int n, int m);
Matrix(const Matrix &X);
~Matrix();
void setMatrix(const float *pvalue);
void printMatrix() const;
inline float &element(int i, int j){
return *(p+i*cols+j);
}
inline float element(int i, int j) const;
void setElement(int i, int j, int value);
inline int getLines() const{
return lines;
}
inline int getCols() const{
return cols;
}
private:
int lines;
int cols;
float *p;
};
#include"matrix.h"
#include<iostream>
using namespace std;
Matrix::Matrix(int n):lines(n),cols(n){
}
Matrix::Matrix(int n,int m):lines(n),cols(m){
}
Matrix::Matrix(const Matrix &X){
lines=X.lines;
cols=X.cols;
p=X.p;
}
void Matrix::setMatrix(const float *pvalue){
p=(float*)pvalue;
}
void Matrix::printMatrix() const{
int i,j;
for(i=0;i<lines;i++){
for(j=0;j<cols;j++)
cout<<*(p+i*cols+j)<<" ";
cout<<endl;
}
}
Matrix::~Matrix(){
}
void Matrix::setElement(int i, int j, int value){
*(p+i*cols+j)=value;
}