C++Primer 第9章-顺序容器-课后习题答案 下载本文

内容发布更新时间 : 2024/5/16 3:36:37星期一 下面是文章的全部内容请认真阅读。

}

{ }

ivec.push_back( 0 );

// add one more ivec.push_back(0);

// show the current capacity of the vector cout << \ << ivec.size() << endl << \ << ivec.capacity() << endl;

system(\); return 0;

31.容器的容量可以比其长度小吗?在初始时或插入元素后,容量是否恰好等于所需要的长度?为什么? 不能。

在初始时,或插入元素后,容量不会恰好等于所需要的长度,一般会大于长度,因为系统会根据一定的分配策略预留一些额外的存储空间以备容器的增长,从而避免了重新分配内存、复制元素、释放内存等操作,提高性能。

32.解释下面程序实现的功能: vector svec; svec.reserve( 1024 ); string text_word;

while ( cin >> text_word ) svec.push_back( text_word ); svec.resize( svec.size() + svec.size()/2 );

如果该程序读入了256个单词,在调整大小后,该容器的容量可能是多少?如果读入512,或1000,或1048个单词呢?

功能:将svec的size设定为1024,然后从标准输入设备读入一系列单词,最后将该vector对象的大小调整为所读入单词个数的1.5倍。

当读入256或512时,容器的容量不变,仍为1024,因为容器大小没有超出已分配内存容量。调整大小只改变容器中有效元素的个数,不会改变容量。 当读入1000时,最后调整容量时,需要1500个元素的存储空间,超过了已分配的容量1024,所以可能重新分配为1536的容量。

当读入1048时,在读入1025个时,容器的容量可能会增长为1536,最后输入完1048个单词后,在调整大小后,需要1572个元素的存储空间,超过了已分配的1536,因此再次重分配,容量再增长0.5倍,变为2304。

33.对于下列程序任务,采用哪种容器实现最合适?解释选择的理由。如果无法说明采用某种容器比另一种容器更好的原因,请解释为什么?

(a) 从一个文件中读入未知数目的单词,以生成英文句子。

(b) 读入固定数目的单词,在输入时将它们按字母顺序插入到容器中,下一章将介绍何时处理此类问题的关联容器。

(c) 读入未知数目的单词,总是在容器尾部插入新单词,从容器首部删除下一个值。 (d) 从一个文件中读入未知数目的整数。对这些整数排序,然后把它们输出到标准输出设备。 (a) 以给确定的顺序随机处理这些单词,采用vector最合适。 (b) list何时,因为需要在容器的任意位置插入元素。

(c) deque合适,因为总是在尾部和首部进行插入和删除的操作。 (d) 如果一边输入一边排序,则采用list合适,如果先读入所有的整数,然后排序,则用vector合适,因为进行排序最好有随机访问的能力。

34.使用迭代器将string对象中的字符都改为大写字母。

// 11.15_9.34_string_toupper.cpp : 定义控制台应用程序的入口点。 //

#include \#include #include

using namespace std;

int _tmain(int argc, _TCHAR* argv[]) { string str; cout << \; cin >> str; cout << \ << str << endl; for ( string::iterator it = str.begin(); it != str.end(); ++it ) { *it = toupper( *it ); } cout << \ << str << endl; system(\); return 0; }

35.使用迭代器寻找和删除string对象中所有的大写字符。 #include \#include #include using namespace std;

int _tmain(int argc, _TCHAR* argv[]) { string str; cout << \; cin >> str; cout << \ << str << endl; for ( string::iterator it = str.begin(); it != str.end(); ++it ) { if ( isupper( *it ) ) { str.erase( it ); it--;

}

}

}

cout << \ << str << endl; system(\); return 0;

36.编写程序用vector容器初始化string对象。

// 11.15_9.36_vectorCharToString.cpp : 定义控制台应用程序的入口点。 //

#include \#include #include #include using namespace std;

int _tmain(int argc, _TCHAR* argv[]) { vector cVec; char cVal; cout << \; while ( cin >> cVal ) cVec.push_back( cVal ); string str( cVec.begin(), cVec.end() ); cout << \ << str << endl; system(\); return 0; }