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

内容发布更新时间 : 2024/5/19 6:54:32星期一 下面是文章的全部内容请认真阅读。

int _tmain(int argc, _TCHAR* argv[]) { cout << \ << endl; list iLst; int iVal; while ( cin >> iVal ) { if ( iVal == 999 ) break; iLst.push_back( iVal ); } cout << \ << endl; vector iVec; int i; while ( cin >> i ) { if ( i == 888 ) break; iVec.push_back( i ); } bool bSame = true; if ( iLst.size() != iVec.size() ) { bSame = false; } else { list::iterator it_l = iLst.begin(); vector::iterator it_v = iVec.begin(); while ( it_l != iLst.end() ) { if ( *it_l != *it_v ) { bSame = false; break; } it_l++; it_v++; } }

}

if ( bSame ) { cout << \ << endl; } else cout << \ << endl;

system(\); return 0;

21.假设c1和c2都是容器,下列用法给c1和c2的元素类型带来什么约束? if ( c1 < c2 )

(如果有的话)对c1和c2的约束又是什么?

c1和c2的元素类型的约束为:类型必须相同,且必须都支持 < 操作符。

22.已知容器vec存放了25个元素,那么vec.resize(100)操作实现了什么功能? 若再做操作vec.resize(10),实现的功能又是什么?

将vec的大小改为100,且把新添加的元素值初始化。 又将vec的后90个元素删除,将vec的大小改为10

23.使用只带有一个长度参数的resize操作对元素类型有什么要求? 对容器里存放的数据类型必须支持值默认初始化。

24.编写程序获取vector容器的第一个元素。分别使用下标操作符,front函数以及begin函数实现该功能,并提供空的vector容器测试你的程序。

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

#include \#include #include using namespace std;

int _tmain(int argc, _TCHAR* argv[]) { cout << \ << endl; vector iVec; int i; while ( cin >> i ) { iVec.push_back( i ); } if ( !iVec.empty() ) { cout << \; cout <<\ << iVec.front(); cout <<\ << *iVec.begin(); cout <<\ << iVec[0]; cout <<\ << iVec.at(0) << endl; } system(\); return 0; }

当用空的vector时,会产生运行时错误,或者抛出异常(使用 vec.at(0) 时).

25.需要删除一段元素时,如果val1和val2相等, 那么程序会发生什么事情?如果val1和val2中的一个不存在,或两个都不存在,程序又会怎么样? 相等,则不会删除任何元素;

若有一个不存在,则会发生运行时错误;

26.假设有如下ia的定义,将ia复制到一个vector容器和一个list容器中。使用单个迭代器参数版本的erase函数将list容器中的奇数值元素删除掉,然后将vector容器中的偶数值元素删除掉。

int ia[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89 };

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

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

int _tmain(int argc, _TCHAR* argv[]) { int ia[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89 }; vector iVec( ia, ia+11 ); list iLst( ia, ia+11 ); cout << \ Before erase, the elements of iVec are:\ << endl; for ( vector::iterator it = iVec.begin(); it != iVec.end(); ++it ) cout << *it << \; cout << \ Before erase, the elements of iLst are:\ << endl; for ( list::iterator it = iLst.begin(); it != iLst.end(); ++it ) cout << *it << \; // 2 erase for ( vector::iterator iter = iVec.begin(); iter != iVec.end(); ++iter ) { if ( *iter % 2 == 0 ) { iter = iVec.erase( iter ); } } for ( list::iterator Lit = iLst.begin(); Lit != iLst.end(); ++Lit ) { if ( *Lit % 2 == 1 ) { Lit = iLst.erase( Lit ); --Lit; } }