#include <iostream> #include <vector> #include <string> using namespace std; // 函数声明 void output1(vector<string> &); void output2(vector<string> &); int main() { vector<string>likes, dislikes; // 创建vector<string>对象likes和dislikes // 为vector<string>数组对象likes添加元素值 ( favorite book, music, film, paintings,anime,sport,sportsman,etc) // 补足代码 likes.push_back("basketball"); likes.push_back("Windfall") ; likes.push_back("Xenogenesis"); cout << "-----I like these-----" << endl; // 调用子函数输出vector<string>数组对象likes的元素值 output1(likes); // 为vector<string>数组对象dislikes添加元素值 // 补足代码 dislikes.push_back("one"); dislikes.push_back("two"); dislikes.push_back("four"); cout << "-----I dislike these-----" << endl; // 调用子函数输出vector<string>数组对象dislikes的元素值 // 补足代码 output1(dislikes); // 交换vector<string>对象likes和dislikes的元素值 // 补足代码 likes.swap(dislikes); cout << "-----I likes these-----" << endl; // 调用子函数输出vector<string>数组对象likes的元素值 // 补足代码 output2(likes); cout << "-----I dislikes these-----" << endl; // 调用子函数输出vector<string>数组对象dislikes的元素值 // 补足代码 output2(dislikes); return 0; } // 函数实现 // 以下标方式输出vector<string>数组对象v的元素值 void output1(vector<string> &v) { // 补足程序 for(int i=0;i<v.size();i++) cout<<v[i]<<endl; cout<<endl; } // 函数实现 // 以迭代器方式输出vector<string>数组对象v的元素值 void output2(vector<string> &v) { // 补足程序 for(vector<string>::iterator iter=v.begin();iter!=v.end();++iter) cout<<*iter<<endl; cout<<endl; }
6-17
#include <iostream> using namespace std; int main() { int *p; p =new int(9); cout << "The value at p: " << *p;
delete p; return 0; }
指针是指向一个地址的,其本身没有意义,直接赋值并没有分配内存空间给它,所以用new申请内存空间来存放这个值//应该是这样吧--
6-18
#include <iostream> using namespace std; int fnl() { int *p=new int(5); return *p; delete p; } int main() { int a = fnl(); cout << "The value of a is: " << a; system("pause"); return 0; }
内存泄漏,用delete释放
#include<iostream> #include<cstdlib> #include<time.h> using namespace std; class Dice { public: Dice(int n); int cast(); private: int sides; }; Dice::Dice(int n) :sides(n) {} int Dice::cast() { return rand() % sides + 1; } int main() { Dice num(40); srand(time(NULL)); int temp; int count = 0; for (int i = 0; i < 500; i++) { temp = num.cast(); if (temp == 6) count++; } cout << count / 500.0 << endl; system("pause"); return 0; }
ran是伪随机,所以用了<time.h>当前时间作为种子,算是比较像真随机吧。