C++ Primer習題5.18

題目:編寫程序定義一個 vector 對象,其每個元素都是指向 string 類型的指針,讀取該 vector 對象,輸出每個 string 的內容及其相應的長度。

#include<iostream>
#include<string>
#include<vector>
using namespace std;

int main()
{
    /*普通
    vector<string> svec;
    string str;
    cout << "Enter some strings(Ctr+Z to end): " << endl;
    while(getline(cin, str))
    {
        svec.push_back(str);
    }
    vector<string>::iterator iter1 = svec.begin(), iter2 = svec.end();
    for(; iter1 != iter2; ++iter1)
    cout << *iter1 << "\t\t" << endl;
    cout << "The length of the svec is: " << svec.end() - svec.begin() << endl;
    */
    vector<string*> spvec;
    //讀取vector變量
    string str;
    cout << "Enter some strings(Ctr+Z to end): " << endl;
    while(getline(cin, str))
    {
        string *pstr = new string;      //指向string對象的指針
        *pstr = str;
        spvec.push_back(pstr);
        //delete pstr;                  //此處會引起程序崩潰,在最後會刪除動態分配對象的。
    }
    //輸出每個string的內容和其相應的長度
    vector<string*>::iterator iter = spvec.begin();
    while(iter != spvec.end())      //此處不可用iter++,否則輸出相當於++iter,即第一個spvec沒有輸出,並企圖輸出一個多餘的元素進行解引用
    {
        cout << **iter << "\t\tthe length of \"" << **iter << "\" is: \t" << (**iter).size() << endl;
        iter++;
    }
    cout << "The length of spvec is: " << spvec.end() - spvec.begin() << endl;
    //釋放給個動態分配的string對象
    iter = spvec.begin();
    while(iter != spvec.end())      //此處不可用iter++,否則輸出相當於++iter,即第一個spvec沒有輸出,並企圖輸出一個多餘的元素進行解引用
    {
        delete *iter;               //刪除動態分配的string對象,有效回收內存,防止”內存泄露“
        iter++;
    }
    return 0;
}


——桑海整理


發佈了47 篇原創文章 · 獲贊 44 · 訪問量 55萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章