C++ Primer(第五版)|練習題答案與解析(第九章:順序容器)

C++ Primer(第五版)|練習題答案與解析(第九章:順序容器)

本博客主要記錄C++ Primer(第五版)中的練習題答案與解析。
參考:C++ Primer
C++ Primer

練習題9.1

對於下面的程序任務,vector, deque和list哪種容器最爲合適?解釋你選擇的理由。如果沒有哪一種容器優於其它容器,也請解釋理由。

(a)讀取固定數量的單詞,將它們按字典序插入到容器中。我們將在下一章看到,關聯容器更適合這個問題。

  • 使用list,需要在中間插入,用list效率更高。

(b)讀取未知數量的單詞,總是將新單詞插入到末尾。刪除操作在頭部進行。

  • 使用deque。只在頭尾進行操作,deque效率更高。

(c)從一個文件中讀取未知數量的整數。將這些整數排序,然後打印到標準輸出。

  • 使用vector。排序需要不斷調整位置,vector支持快速隨機訪問,用vector更適合。

練習題9.2

定義一個list對象,其元素類型是int的deque。

爲:list<deque<int>>;

練習題9.3

構成迭代器範圍的迭代器有和限制。

begin和end構成了迭代器範圍(P296):

  • 其必須分別指向同一個容器的元素或是尾元素之後的位置。
  • 可以通過反覆遞增begin來到達end。

練習題9.4

編寫一個函數,接受一對指向vector的迭代器和一個int值。在兩個迭代器指定的範圍中查找給定的值,返回一個布爾值來指出是否找到。

bool findVal(vector<int>::const_iterator beg, vector<int>::const_iterator end, int val)
{
    while (beg != end) {
        if (*beg != val) {
            beg ++;
        }
        else {
            return true;
        }
    }
    return false;
}

練習題9.5

重寫上一題的函數,返回一個迭代器指向找到的元素。注意,程序必須處理未找到給定值的情況。

int findVal1(vector<int>::const_iterator beg, vector<int>::const_iterator end, int val)
{
    while (beg != end) {
        if (*beg != val) {
            beg ++;
        }
        else {
            return *beg;
        }
    }
    return *end;
}

練習題9.6

下面程序有何錯誤?你應該如何修改?

list<int> lstl;
list<int>::iterator iter1 = lstl.begin(),
                   iter2 = lstl.end();
while (iter1 < iter2)   /* ... */

迭代器之間沒有大於小於的比較(比較地址的大小沒有必要)。修改爲:while(iter1 != iter2)(P297)

練習題9.7

爲了索引int的vector中的元素,應該使用什麼類型?

索引應該是爲了便於查找,保存元素的位置。應該是unsigned int類型,所以爲vector<int>::size_type;

練習題9.8

爲了讀取string的list的元素,應該使用什麼類型?如果寫入list,又該使用什麼類型?

//讀操作
list<string>::const_iterator iter;
//寫操作
list<string>::iterator iter;

練習題9.9

begin和cbegin兩個函數有什麼不同?

begin函數返回的是普通的iterator,而cbegin返回的是const_iterator(P298)。

練習題9.10

下面4個對象分別是什麼類型?

vector<int> v1;
const vector<int> v2;
auto it1 = v1.begin(), it2 = v2.begin();
auto it3 = v1.cbegin(), it4 = v2.cbegin();
// it1:iterator類型。it2,it3,it4是const_iterator類型。

練習題9.11

對6種創建和初始化vector對象的方法,每一種都給出一個實例。解釋每個vector包含什麼值。

vector<int> ivec1;                      // 空
vector<int> ivec2{1, 2, 3, 4, 5};       // 1, 2, 3, 4, 5
vector<int> ivec3 = {6, 7, 8, 9, 10};   // 6, 7, 8, 9, 10
vector<int> ivec4(ivec2);               // 1, 2, 3, 4, 5
vector<int> ivec5 = ivec3;              // 6, 7, 8, 9, 10
vector<int> ivec6(10, 4);               // 10個4

練習題9.12

對於接受一個容器創建其拷貝的構造函數,和接受兩個迭代器創建拷貝的構造函數,解釋它們的不同。

  • 接受一個容器創建其拷貝的構造函數,要求兩個容器類型及元素類型必須匹配。
  • 接受兩個迭代器創建拷貝的構造函數,不要求容器類型匹配,而且元素類型也可以不同,只要拷貝的元素能轉換就可以。

練習題9.13

如何用一個list初始化一個vector?從一個vector又該如何創建?編寫代碼驗證你的答案。

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <list>
using namespace std;
int main()
{
    list<int> ilst(5, 4);
    vector<int> ivc(5, 5);
    // from list<int> to vector<double>
    vector<double> dvc(ilst.begin(), ilst.end());
    for (auto i : ilst) cout << i << " ";
    cout << endl;
    for (auto d : dvc) cout << d << " ";
    cout << endl;
    // from vector<int> to vector<double>
    vector<double> dvc2(ivc.begin(), ivc.end());
    for (auto i : ivc) cout << i << " ";
    cout << endl;
    for (auto d : dvc2) cout << d << " ";

    return 0;
}

測試:

4 4 4 4 4
4 4 4 4 4
5 5 5 5 5
5 5 5 5 5

練習題9.14

編寫程序,將一個list中的char*指針(指向C風格字符串)元素賦值給一個vector中的string。

#include <iostream>
#include <vector>
#include <string>
#include <list>
using namespace std;
int main()
{
    list<const char*> l{ "Mooophy", "pezy", "Queeuqueg" };
    vector<std::string> v;
    v.assign(l.cbegin(), l.cend());
    for (auto ptr : v)
        cout << ptr << endl;

    return 0;
}

測試:

Mooophy
pezy
Queeuqueg

練習題9.15

編寫程序,判定兩個vector是否相等。

#include <iostream>
#include <vector>
#include <string>
#include <list>
using namespace std;
int main()
{
    vector<int> vec1{ 1, 2, 3, 4, 5 };
    vector<int> vec2{ 1, 2, 3, 4, 5 };
    vector<int> vec3{ 1, 2, 3, 4 };

    cout << (vec1 == vec2 ? "true" : "false") << endl;
    cout << (vec1 == vec3 ? "true" : "false") << endl;

    return 0;
}

測試:

true
false

練習題9.16

重寫上一題的程序,比較一個list中的一個元素和一個vector中的元素。

#include <iostream>
#include <vector>
#include <string>
#include <list>
int main()
{
    std::list<int>      li{ 1, 2, 3, 4, 5 };
    std::vector<int>    vec2{ 1, 2, 3, 4, 5 };
    std::vector<int>    vec3{ 1, 2, 3, 4 };
    std::cout << (std::vector<int>(li.begin(), li.end()) == vec2 ? "true" : "false") << std::endl;
    std::cout << (std::vector<int>(li.begin(), li.end()) == vec3 ? "true" : "false") << std::endl;

    return 0;
}

測試:

true
false

練習題9.17

假定c1和c2是兩個容器,下面的比較操作有何限制(如果有的話)?
if (c1 < c2)

  • 要求c1和c2必須是同類容器,其中元素也必須是同種類型。
  • 該容器必須支持比較關係運算。

練習題9.18

編寫程序,從標準輸入讀取string序列,存入一個deque中。編寫一個循環,用迭代器打印deque中的元素。

#include <iostream>
#include <string>
#include <deque>
using namespace std;
int main()
{
    deque<string> input;
    for (string str; cin >> str; input.push_back(str));
    for (auto iter = input.cbegin(); iter != input.cend(); ++iter)
        cout << *iter << endl;

    return 0;
}

測試:

This is a C++
^Z
This
is
a
C++

練習題9.19

重寫上題程序,用list代替deque。列出程序要做出哪些改變。

#include <iostream>
#include <string>
#include <list>
using namespace std;
int main()
{
    list<string> input;
    for (string str; cin >> str; input.push_back(str));
    for (auto iter = input.cbegin(); iter != input.cend(); ++iter)
        cout << *iter << endl;

    return 0;
}
  • 將deque改爲list類型
  • iterator的類型也改爲list即可,如果是使用auto就不用了。

練習題9.20

編寫程序,從一個list拷貝元素到兩個deque中。值爲偶數的所有元素都拷貝到一個deque中,而奇數值元素都拷貝到另一個deque中。

#include <iostream>
#include <deque>
#include <list>
using namespace std;
int main()
{
    list<int> l{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    deque<int> odd, even;
    for (auto i : l)
        (i & 0x1 ? odd : even).push_back(i);
    for (auto i : odd) cout << i << " ";
    cout << endl;
    for (auto i : even)cout << i << " ";
    cout << endl;

    return 0;
}

測試:

1 3 5 7 9
2 4 6 8 10

練習題9.21

如果我們將308頁中使用insert返回值將元素添加到list中的循環程序改寫爲將元素插入到vector中,分析循環將如何工作。

#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
    vector<string> svec;
    string word;
    auto beg = svec.begin();
    while (cin >> word) {
        beg = svec.insert(beg, word);
    }
    for(auto c:svec)
        cout<<c<<" ";
    return 0;
}

測試:

This is a C++
^Z
C++ a is This

練習題9.22

假定iv是一個int的vector,下面的程序存在什麼錯誤?你將如何修改?

vector<int>::iterator iter = iv.begin(),
                    mid = iv.begin() + iv.size()/2;

while(iter != mid) {
    if (*iter == some_val) {
        iv.insert(iter, 2 * some_val);      
    }
}

修改爲:

#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
    vector<int> iv  = {1, 3, 5};
    iv.reserve(5);
    // 必須要又足夠的容量,否則size爲3,插入一個元素之後size超出,iter就會失效,指向未知地址。
    int some_val = 1;

    vector<int>::iterator iter = iv.begin(),
                    mid = iv.begin() + iv.size()/2;

    while(iter != mid) {
        if (*iter == some_val) {
            mid = iv.insert(iter, 2 * some_val);
            // insert操作要接收返回的迭代器,如果賦給iter,則iter和mid永遠不會相等,因爲mid也會隨之改變。mid接收,mid就和iter都指向首元素了
        }
        else {
            mid --;
        }
    }
    return 0;
}

練習題9.23

在本節第一個程序(309頁)中,若c.size()爲1, 則val, val2, val3和val4的值會是什麼?

將會全部指向c容器的首元素。

練習題9.24

編寫程序,分別使用at、下標運算符、front和begin提取一個vector中的第一個元素。在一個空vector上測試你的程序。

#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
    std::vector<int> v;
    std::cout << v.at(0);       // terminating with uncaught exception of type std::out_of_range
    std::cout << v[0];          // Segmentation fault: 11
    std::cout << v.front();     // Segmentation fault: 11
    std::cout << *v.begin();    // Segmentation fault: 11
    return 0;
}
terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check: __n (which is 0) >= this->size() (which is 0)

練習題9.25

對於312頁中刪除一個範圍內的元素的程序,如果elem1與elem2相等會發生什麼?如果elem2是尾後迭代器,或者elem1和elem2皆爲尾後迭代器,又會發生什麼?

  • 如果elem1和elem2相等,則不發生刪除操作。
  • 如果elem2是尾後迭代器,則刪除elem1之後的元素,返回尾後迭代器。
  • 如果elem1和elem2都是尾後迭代器,則不發生刪除操作。

練習題9.26

使用下面代碼定義的ia,將ia拷貝到一個從vector和一個list中。使用單迭代器版本的erase從list中刪除奇數元素,從vector中刪除偶數元素。
int ia[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89};

#include <iostream>
#include <vector>
#include <list>
using namespace std;
int main()
{
    int ia[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89 };

    // 初始化
    vector<int> vec(ia, end(ia));
    list<int> lst(vec.begin(), vec.end());

    // 移除奇數值
    for(auto it = lst.begin();  it != lst.end(); )
        if(*it & 0x1) it = lst.erase(it);
        else ++it;

    // 移除偶數值
    for(auto it = vec.begin();  it != vec.end(); )
        if(! (*it & 0x1)) it = vec.erase(it);
        else ++it;

    // 查看結果
    cout << "list : ";
    for(auto i : lst)   cout << i << " ";
    cout << "\nvector : ";
    for(auto i : vec)   cout << i << " ";
    cout << std::endl;

    return 0;
}

測試

list : 0 2 8
vector : 1 1 3 5 13 21 55 89

練習題9.27

編寫程序,查找並刪除forward_list中的奇數元素。

#include <iostream>
#include <vector>
#include <forward_list>
using namespace std;
int main()
{
    int ia[] = {0, 1, 1, 2, 3, 5, 8, 13, 15,16};
    forward_list<int> iflst (begin(ia), end(ia));
    auto prev = iflst.before_begin();
    auto curr = iflst.begin();

    while (curr != iflst.end()) {
        if (*curr % 2) {
            curr = iflst.erase_after(prev);
        }
        else {
            prev = curr;
            ++curr;
        }
    }
    for(auto i : iflst)
        cout<<i<<" ";
    return 0;
}

測試:

0 2 8 16

練習題9.28

編寫函數,接受一個forward_list和兩個string共三個參數。函數應在鏈表中查找第一個string,並將第二個string插入到緊接着第一個string之後的位置。若第一個string未在鏈表中,則將第二個string插入到鏈表末尾。

void insertToFlst(forward_list<string>& sflst, const string& val_in_flst, const string& val_to_insert)
{
    auto prev = sflst.before_begin();
    auto curr = sflst.begin();


    while (curr != sflst.end()) {
        if (*curr == val_in_flst) {
            sflst.insert_after(curr, val_to_insert);
            return;
        }
        else {
            prev = curr;
            ++ curr;
        }
    }
    sflst.insert_after(curr, val_to_insert);
}

練習題9.29

假定vec包含25個元素,那麼vec.resize(100)會做什麼?如果接下來調用vec.resize(10)會做什麼?

vec.resize(100)會把75個值爲0的值添加到vec的結尾。

vec.resize(10)會把vec末尾的90個元素刪除掉。

練習題9.30

接受單個參數的resize版本對元素類型有什麼限制(如果有的話)?

如果容器保存的是類類型元素,則使用resize必須提供初始值,或元素類型必須提供一個默認構造函數。

練習題9.31

第316頁中刪除偶數值元素並複製奇數值元素的程序不能用於list或forward_list。爲什麼?修改程序,使之也能用於這些類型。

listforward_list的迭代器不支持加減操作,因爲鏈表的內存不連續,無法通過加減操作來尋址。
使用advance()可令迭代器前進C++ STL一一迭代器相關輔助函數
list:

#include <iostream>
#include <list>
using std::list;
using std::cout;
using std::advance;
auto remove_evens_and_double_odds(list<int>& data)
{
    for(auto cur = data.begin(); cur != data.end();)
        if (*cur & 0x1)
            cur = data.insert(cur, *cur), advance(cur, 2);
        else
            cur = data.erase(cur);
}
int main()
{
    list<int> data { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    remove_evens_and_double_odds(data);
    for (auto i : data) cout << i << " ";
    return 0;
}

forward_list

#include <iostream>
#include <forward_list>
using std::forward_list;
using std::cout;
using std::advance;
auto remove_evens_and_double_odds(forward_list<int>& data)
{
    for(auto cur = data.begin(), prv = data.before_begin(); cur != data.end();)
        if (*cur & 0x1)
            cur = data.insert_after(prv, *cur),
            advance(cur, 2),
            advance(prv, 2);
        else
            cur = data.erase_after(prv);
}
int main()
{
    forward_list<int> data { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    remove_evens_and_double_odds(data);
    for (auto i : data)
        cout << i << " ";
    return 0;
}

練習題9.32

再316頁的程序中,向下面語句這樣調用insert是否合法?如果不合法,爲什麼?
iter = vi.insert(iter, *iter++);

不合法,因爲編譯器不知道應該先執行insert操作,還是執行*iter++操作。或者執行完insert之後,應該先返回,還是對iter進行++操作。

練習題9.33

在本節最後一個例子中,如果不將insert的結果賦予begin,將會發生什麼?編寫程序,去掉此賦值語句,驗證你的答案。

程序崩潰,因爲迭代器將會失效。

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<int> ivec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    auto iter = ivec.begin();
    while (iter != ivec.end()) {
        ++ iter;
        /* iter = */ivec.insert(iter, 42);
        ++ iter;
    }
    for(auto i : ivec)
        cout<<i<<" ";
    return 0;
}

練習題9.34

假定vi是一個保存int的容器,其中有偶數值也要奇數值,分析下面循環的行爲,然後編寫程序驗證你的分析是否正確。

iter = vi.begin();
while (iter != vi.end())
    if (*iter % 2)
        iter = vi.insert(iter, *iter);
    ++ iter;

不正確,insert是插入到iter之前,返回的是新插入元素的迭代器,因此在插入元素之後,應該加兩次,才能到原始的下一個元素。
修改爲:

    auto iter = ivec.begin();
    while (iter != ivec.end()) {
        if (*iter % 2) {
            iter = ivec.insert(iter, *iter);
            ++ iter;
        }
        ++ iter;
    }

練習題9.35

解釋一個vector的capacity和size有何區別?

size是指它已經保存的元素數目,而capacity則是在不分配新的內存空間的前提下最多可以保存的元素(P318)。

練習題9.36

一個容器的capacity可能小於它的size嗎?

不可能,當容量不夠,繼續添加元素時,容器會自動擴充容量,具體添加多少看標準庫的實現(P319)。capacity>=size。

練習題9.37

爲什麼list或array沒有capacity成員函數?

  • 因爲array時固定長度的。
  • list不是連續內存,不需要capacity。

練習題9.38

編寫程序,探究在你的標準庫實現中,vector是如何增長的?

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<int> ivec;
    int value;
    while (cin >> value) {
        ivec.push_back(value);
        cout << "the vector's size = " << ivec.size() << endl;
        cout << "the vector's capacity = " << ivec.capacity() << endl;
    }
    return 0;
}

測試:

10
the vector's size = 1
the vector's capacity = 1
10
the vector's size = 2
the vector's capacity = 2
10
the vector's size = 3
the vector's capacity = 4
10
the vector's size = 4
the vector's capacity = 4
10
the vector's size = 5
the vector's capacity = 8

可以發現capacity成雙倍增長。

練習題9.39

解釋下面程序片段做了什麼?

vector<string> svec;
svec.reserve(1024);
string word;
while (cin >> word) {
    svec.push_back(word);
}
svec.resize(svec.size() + svec.size()/2);

先給一個vector分配1024大小的空間,將輸入的值保存進vector。如果輸入的元素大於1024,vector會自動擴容。最後使用resize只能改變vector的size,不能改變其capacity。

練習題9.40

如果上一題的程序讀入了256個詞,在resize之後容器的capacity可能是多少?如果讀入了512個、1000個或1048個詞呢?

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<string> svec;
    svec.reserve(1024);
    string word = "word";
    int count;
    cin>>count;
    for(int i = 0; i < count; ++i)
        svec.push_back(word);
    svec.resize(svec.size() + svec.size()/2);
    cout<<"count   :"<<count<<endl;
    cout<<"size    :"<<svec.size()<<endl;
    cout<<"capacity:"<<svec.capacity()<<endl;
    return 0;
}

測試:

256
count   :256
size    :384
capacity:1024

512
count   :512
size    :768
capacity:1024

1000
count   :1000
size    :1500
capacity:2000

1048
count   :1048
size    :1572
capacity:2048

練習題9.41

編寫程序,從一個vector初始化一個string。

#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
    vector<char> v{ 'p', 'e', 'z', 'y' };
    string str(v.cbegin(), v.cend());
    cout << str << endl;

    return 0;
}

測試:

pezy

練習題9.42

假定你希望每次讀取一個字符存入一個string中,而且知道最少需要讀取100個字符,應該如何提高性能。

利用reserve操作預留足夠的內存,這樣就不用在過程中重新分配內存了。

練習題9.43

假定你希望每次讀取一個字符存入一個string中,而且知道最少需要讀取100個字符,應該如何提高性能。

#include <iostream>
#include <vector>
#include <string>
using namespace std;
void replaceStr(string& s, string& oldVal, string& newVal)
{
    int old_size = oldVal.size();
    auto iter_s = s.begin();
    auto iter_old = oldVal.begin();
    auto iter_new = newVal.begin();

    for (iter_s; iter_s <= (s.end()-oldVal.size()+1); ++ iter_s) {
        if (s.substr((iter_s-s.begin()), old_size) == oldVal) {
            iter_s = s.erase(iter_s, iter_s+old_size);
            // iter_s指向刪除元素的下一個元素
            iter_s = s.insert(iter_s, newVal.begin(), newVal.end());//這句報錯 未找到原因
            // iter_s指向插入元素的前一個元素,必須要用iter_s接收返回值,否則原有的迭代器失效。
            advance(iter_s, oldVal.size());  // 跳過已經替換的string。
        }
    }
}
int main()
{
    vector<char> v{ 'p', 'e', 'z', 'y' };
    string str(v.cbegin(), v.cend());
    cout << str << endl;

    return 0;
}

練習題9.44

重寫上一題的函數,這次使用一個下標和replace。

#include <iostream>
#include <vector>
#include <string>
using namespace std;
void replace_with(string &s, string const& oldVal, string const& newVal)
{
    for (size_t pos = 0; pos <= s.size() - oldVal.size();)
        if (s[pos] == oldVal[0] && s.substr(pos, oldVal.size()) == oldVal)
            s.replace(pos, oldVal.size(), newVal),
            pos += newVal.size();
        else
            ++pos;
}
int main()
{
    string str{ "To drive straight thru is a foolish, tho courageous act." };
    replace_with(str, "tho", "though");
    replace_with(str, "thru", "through");
    cout << str << endl;
    return 0;
}

測試

To drive straight through is a foolish, though courageous act.

練習題9.45

重寫上一題的函數,這次使用一個下標和replace。

#include <iostream>
#include <vector>
#include <string>
using namespace std;
// Exercise 9.45
string add_pre_and_suffix(string name, string const& pre, string const& su)
{
    name.insert(name.begin(), pre.cbegin(), pre.cend());
    return name.append(su);
}
int main()
{
    string name("Liu");
    cout << add_pre_and_suffix(name, "Mr.", ", Jr.") << endl;
    return 0;
}

測試

Mr.Liu, Jr.

練習題9.46

重寫上一題的函數,這次使用位置和長度來管理string,並只使用insert。

#include <iostream>
#include <vector>
#include <string>
using namespace std;
// Exercise 9.45
string add_pre_and_suffix(string name, string const& pre, string const& su)
{
    name.insert(0, pre);
    name.insert(name.size(), su);
    return name;
}

int main()
{
    string name("Yang");
    cout << add_pre_and_suffix(name, "Mr.", ",Jr.");
    return 0;
}

測試

Mr.Yang,Jr.

練習題9.47

編寫程序,首先查找string "ab2c3d7R4E6"中的每個數字字符,然後查找其中每個字母字符。編寫兩個版本的程序,第一個要使用find_fisrt_of,第二個要使用find_first_not_of.

版本一

#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
    string numbers{ "123456789" };
    string alphabet{ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" };
    string str{ "ab2c3d7R4E6" };
    cout << "numeric characters: ";
    for (int pos = 0; (pos = str.find_first_of(numbers, pos)) != string::npos; ++pos)
        cout << str[pos] << " ";
    cout << "\nalphabetic characters: ";
    for (int pos = 0; (pos = str.find_first_of(alphabet, pos)) != string::npos; ++pos)
        cout << str[pos] << " ";
    cout << endl;

    return 0;
}

測試:

numeric characters: 2 3 7 4 6
alphabetic characters: a b c d R E

版本二:

#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
    string numbers{ "0123456789" };
    string alphabet{ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" };
    string str{ "ab2c3d7R4E6" };
    cout << "numeric characters: ";
    for (int pos = 0; (pos = str.find_first_not_of(alphabet, pos)) != string::npos; ++pos)
        cout << str[pos] << " ";
    cout << "\nalphabetic characters: ";
    for (int pos = 0; (pos = str.find_first_not_of(numbers, pos)) != string::npos; ++pos)
        cout << str[pos] << " ";
    cout << endl;

    return 0;
}

測試:

numeric characters: 2 3 7 4 6
alphabetic characters: a b c d R E

練習題9.48

假定name和numbers的定義如325頁所示,number.find(name)返回什麼?

#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
    string name = "AnnaBelle";
    string number = "0123456789";
    auto result = number.find(name);
    if (result == string::npos) {
        cout << "npos" << endl;
    }
    return 0;
}

測試:返回npos

練習題9.49

如果一個字母延伸要中線之上,如d或f,則稱其有上出頭部分。如果延伸到中線之下,則稱其有下出頭部分。編寫程序,讀入一個單詞文件,輸出最長的既不包含上出頭部分,也不包含下出頭部分的單詞。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
    string str = "aacgaesse";
    string s = "aceimnorsuvwxz";
    int pos1 = 0, pos2 = 0, pos3 = 0, max_len = 0;
    string result;

    for (pos1; (pos1 = str.find_first_of(s, pos1))!=string::npos; ++ pos1) {
        pos2 = pos1;
        if((pos2 = str.find_first_not_of(s, pos2)) != string::npos)  {
            if ((pos2-pos1) > max_len) {
                max_len = pos2-pos1;
                pos3 = pos1;
                pos1 = pos2;
            }
        } else {
            if (max_len < (str.size() - pos1)) {
                max_len = str.size() - pos1;
                pos3 = pos1;
                break;
            }
        }
    }
    result = str.substr(pos3, max_len);
    cout << result << endl;

    return 0;
}

測試:

aesse

練習題9.50

編寫程序處理一個vector,其元素都表示整形值。計算vector中所有元素之和。修改程序,使之計算表示浮點值的string之和。

#include <iostream>
#include <vector>
#include <string>
int sum_for_int(std::vector<std::string> const& v)
{
    int sum = 0;
    for (auto const& s : v)
        sum += std::stoi(s);
    return sum;
}

float sum_for_float(std::vector<std::string> const& v)
{
    float sum = 0.0;
    for (auto const& s : v)
        sum += std::stof(s);
    return sum;
}

int main()
{
    std::vector<std::string> v = { "1", "2", "3", "4.5" };
    std::cout << sum_for_int(v) << std::endl;
    std::cout << sum_for_float(v) << std::endl;

    return 0;
}

用的時候會找不到stofstoi,待解決。

練習題9.51

設計一個類,它有三個unsigned成員,分別表示年、月和日。爲其編寫構造函數,接受一個表示日期的string參數。你的構造函數應該能處理不同數據格式,如January 1,1900、1/1/1990、Jan 1 1900等。

#include <iostream>
#include <string>
#include <vector>

using namespace std;
class My_date{
private:
    unsigned year, month, day;
public:
    My_date(const string &s){

        unsigned tag;
        unsigned format;
        format = tag = 0;

        // 1/1/1900
        if(s.find_first_of("/")!= string :: npos)
        {
            format = 0x01;
        }

        // January 1, 1900 or Jan 1, 1900
        if((s.find_first_of(',') >= 4) && s.find_first_of(',')!= string :: npos){
            format = 0x10;
        }
        else{ // Jan 1 1900
            if(s.find_first_of(' ') >= 3
                && s.find_first_of(' ')!= string :: npos){
                format = 0x10;
                tag = 1;
            }
        }

        switch(format){

        case 0x01:
            day = stoi(s.substr(0, s.find_first_of("/")));
            month = stoi(s.substr(s.find_first_of("/") + 1, s.find_last_of("/")- s.find_first_of("/")));
            year = stoi(s.substr(s.find_last_of("/") + 1, 4));

        break;

        case 0x10:
            if( s.find("Jan") < s.size() )  month = 1;
            if( s.find("Feb") < s.size() )  month = 2;
            if( s.find("Mar") < s.size() )  month = 3;
            if( s.find("Apr") < s.size() )  month = 4;
            if( s.find("May") < s.size() )  month = 5;
            if( s.find("Jun") < s.size() )  month = 6;
            if( s.find("Jul") < s.size() )  month = 7;
            if( s.find("Aug") < s.size() )  month = 8;
            if( s.find("Sep") < s.size() )  month = 9;
            if( s.find("Oct") < s.size() )  month =10;
            if( s.find("Nov") < s.size() )  month =11;
            if( s.find("Dec") < s.size() )  month =12;

            char chr = ',';
            if(tag == 1){
                chr = ' ';
            }
            day = stoi(s.substr(s.find_first_of("123456789"), s.find_first_of(chr) - s.find_first_of("123456789")));

            year = stoi(s.substr(s.find_last_of(' ') + 1, 4));
            break;
        }
    }

    void print(){
        cout << "day:" << day << " " << "month: " << month << " " << "year: " << year;
    }
};
int main()
{
    My_date d("Jan 1 1900");
    d.print();
    return 0;
}

練習題9.52

使用stack處理括號化的表達式。當你看到一個左括號,將其記錄下來。當在一個左括號之後看到一個右括號,從stack中pop對象,直至遇到左括號,將左括號也一起彈出棧。然後將一個值push到棧中,表示一個括號化的表達式已經處理完畢,被其運算結果所替代。

#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main()
{
    string expression{ "This is (a C++)." };
    bool bSeen = false;
    stack<char> stk;
    for (const auto &s : expression)
    {
        if (s == '(') { bSeen = true; continue; }
        else if (s == ')') bSeen = false;
        if (bSeen) stk.push(s);
    }
    string repstr;
    while (!stk.empty())
    {
        repstr += stk.top();
        stk.pop();
    }
    expression.replace(expression.find("(")+1, repstr.size(), repstr);
    cout << expression << endl;
    return 0;
}

測試:

This is (++C a).
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章