new的例子
12.6 編寫函數(shù),返回一個(gè)動(dòng)態(tài)分配的int的vector。將此vector傳遞給另一個(gè)函數(shù),這個(gè)函數(shù)讀取標(biāo)準(zhǔn)輸入,將讀入的值保存在vector元素中。再將vector傳遞給另一個(gè)函數(shù),打印讀入的值。記得在恰當(dāng)?shù)臅r(shí)刻delete vector。
#include<iostream> #include<new> #include<vector> using namespace std; vector<int>* f1() {vector<int> *p=new vector<int>;return p; }vector<int>* f2() {vector<int> *p=f1();int n;while(cin>>n)p->push_back(n);return p; }int main() {vector<int> *p=f2();for(auto v:*p)cout<<v<<" ";delete p;return 0; }12.7 使用shared_ptr而不是內(nèi)置指針。
#include<iostream> #include<vector> #include<memory> using namespace std; shared_ptr<vector<int>> f1() {shared_ptr<vector<int>> p=make_shared<vector<int>>();return p; }shared_ptr<vector<int>> f2() {shared_ptr<vector<int>> p=f1();int n;while(cin>>n)p->push_back(n);return p; }int main() {shared_ptr<vector<int>> p=f2();for(auto v:*p)cout<<v<<" ";return 0; }?
轉(zhuǎn)載于:https://www.cnblogs.com/wuchanming/p/3922406.html
總結(jié)
- 上一篇: Android 使用NineOldAnd
- 下一篇: 本科生怎样发表论文?