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).
发布了76 篇原创文章 · 获赞 44 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_24739717/article/details/104353712