天天看點

C++Primer第五版 第九章習題答案(1~10)

1:知識點1:幾種順序容器的特點

vector:可變大小,支援快速随機通路,尾部插入資料很快

deque:雙端隊列。支援快速随機通路,頭部插入資料很快

list:雙向連結清單。支援雙向順序通路,在其任何位置插入删除資料都很快

array:固定大小數組,不能改變大小。(注意這裡與普通的内置數組類型是不一樣的)

string:與vector類似,專用于儲存字元。

知識點2:在通常情況下,使用vector是非常好的選擇。且新版本的标準庫容器比舊版本快很多。C++程式應該使用标準庫容器,而不是原始的資料結構如:内置數組。

(a)list,因為可能需要在容器的中間位置插入元素

(b)deque,因為需要在頭部進行元素的删除,deque效率更高

(c)vector,無具體的删除插入操作,未知數量,vector是個不錯的選擇。

2:知識點1:容器中的元素類型可以是另一個容器

知識點2:本節中的幾個比較重要的容器操作:

c.empty():c中存儲了元素,傳回false.

c.cbegin():傳回const_iterator

c.clear():清空容器

list<deque<int>>;//舊版本的編譯器需要在兩個尖括号中加空格           

3:知識點1:限制如下:

疊代器指向同一個容器或者最後一個元素之後的位置

可以反複遞增begin直到end

知識點2:疊代器指向的元素範圍是左閉合區間,注意end指向的是最後一個元素之後的位置。

[begin , end)           

4:

#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<vector>
using namespace std;

bool find1(vector<int>::iterator a, vector<int>::iterator b, int c)//疊代器的類型要弄清楚
{
	for (a; a != b; a++)
	{
		if (*a == c)//疊代器需進行解引用操作
		{
			return true;
		}
	}
	return false;
}

int main(int argc, char**argv)
{
	vector<int> vec(20);//必須事先指定這個大小,才知道end的指向
	vec[0] = 4;
	vec[1] = 5;
	vec[2] = 2;
	vec[3] = 8;
	vec[4] = 9;
	vec[5] = 6;
	vec[6] = 7;//使用VS1010,不支援清單初始化,見諒
	int find_member = 1;
	if ( find1(vec.begin(),vec.end(), find_member) )
	{
		cout<<"We have found it"<<endl;
	}
	else
		cout<<"Sorry,there is no "<<find_member<<" in the range"<<endl;
	return 0;
}           

5:

#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<vector>
using namespace std;

vector<int>::iterator find1(vector<int>::iterator a, vector<int>::iterator b, int c)//疊代器的類型要弄清楚
{
	for (a; a != b; a++)
	{
		if (*a == c)//疊代器需進行解引用操作
		{
			return a;
		}
	}
	return b;//未找到的情況,傳回最後一個疊代器
}

int main(int argc, char**argv)
{
	vector<int> vec(20);//必須事先指定這個大小,才知道end的指向
	vec[0] = 4;
	vec[1] = 5;
	vec[2] = 2;
	vec[3] = 8;
	vec[4] = 9;
	vec[5] = 6;
	vec[6] = 7;//使用VS1010,不支援清單初始化,見諒
	int find_member = 1;
	if ( find1(vec.begin(),vec.end(), find_member) != vec.end() )
	{
		cout<<"We have found it"<<endl;
	}
	else
		cout<<"Sorry,there is no "<<find_member<<" in the range"<<endl;
	return 0;
}           

6:疊代器之間無大于小于号的比較

感謝評論區指出問題:兩個疊代器不在統一容器内不能直接比較

while(*iter1 < *iter2)
/*   */           

7:vector<int>::size_type //size_type指的是無符号整數類型

8:知識點:讀和寫的不同,如果要寫則傳回的必然不能是const iterator

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

9:cbegin()傳回的是const iterator,不可被修改

rbegin()傳回的是反向疊代器

10:

it1:vector<int>::iterator

it2:const vector<int>::iterator

it3:vector<int>::const_iterator

it4:const vector<int>::const_iterator

繼續閱讀