更新时间:2022-08-16 09:39:16
习题9.2 创建和初始化一个vector对象有4种方式,为每种方式提供一个例子。
解答:
2. 分配指定数目的元素,并将这些元素初始化为指定值:
3. 将vector对戏那个初始化为一段元素的副本:
4. 将一个vector对象初始化为另一vector对象的副本:
习题9.3 解释复制容器对象的构造函数和使用迭代器的构造函数之间的区别。
解答:
差别在于:
习题9.9 编写一个循环将list容器的元素逆序输出。
实现代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#include<iostream> #include<list> using namespace std;
int main()
{ int ia[5]={1 , 2 , 3 , 4 , 5};
list< int > lst1(ia , ia + 5);
list< int >::iterator iter1 = lst1.begin(),
iter2 = lst1.end();
while (iter2 != iter1)
cout<<*(--iter2)<< " " ;
cout<<endl;
return 0;
} |
习题9.12 编写一个函数,其形参是一对迭代器和一个int型数值,实现在迭代器标记的范围内寻找该int型数值的功能,并返回一个bool结果,以指明是否找到指定数据。
#include<iostream> #include<vector> using namespace std; bool findInt(vector<int>::iterator beg , vector<int>::iterator end , int ival) { while(beg != end) if(*beg == ival) break; else ++beg; if(beg != end) return true; else return false; } int main() { int a[5] = {10 , 13 , 5 , 8}; vector<int> iter(a , a + 5); if(findInt( iter.begin() , iter.end() , 5)) { cout<<"success !"<<endl; } else cout<<"failure!"<<endl; return 0; }
习题9.11 要标记出有效的迭代器范围,迭代器需满足什么约束?
如果迭代器first和last标记出有效的迭代器范围,则必须满足:
习题9.20 编写程序判断一个vector<int>容器所包含的元素是否与一个list<int>容器的完全相同。
//判断一个vector<int>容器所包含的元素 //是否与一个list<int>容器的完全相同 #include<iostream> #include<vector> #include<list> using namespace std; int main() { vector<int> ivec; list<int> ilst; int ival; //读入int对象并存储在vector对象中 cout<<"Enter some integers for vector(Ctrl+z to end): " <<endl; while(cin>>ival) ivec.push_back(ival); cin.clear(); //使流对象重新置为有效状态 //读入int对象并存储在list对象中 cout<<"Enter some integers for list: " <<endl; while(cin>>ival) ilst.push_back(ival); //比较vector对象和list对象中的对应元素 vector<int>::iterator vit = ivec.begin(); list<int>::iterator lit = ilst.begin(); while(vit != ivec.end() && lit != ilst.end()) { if(*vit != *lit) //对应元素不相等则结束循环 break; ++vit; ++lit; } //输出比较结果 if(vit == ivec.end() && lit == ilst.end()) //所有元素都相等 cout<<"The vector contains the same elements as the list." <<endl; else cout<<"List and vector contain different elements." <<endl; return 0; }
注意,因为使用文件结束符作为输入vector元素的结束,所以,读入了所有的vector元素后,流cin处于无效状态,需要将流cin重新置为有效,否则,将无法使用cin继续读入list元素。
微信公众号:
猿人谷
如果您认为阅读这篇博客让您有些收获,不妨点击一下右下角的【推荐】
如果您希望与我交流互动,欢迎关注微信公众号
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。