9.1
(a) list
(b) deque, if you don’t entangle the constant, then list can be
(c) vector
9.2
list<deque<int>> ldi;
9.3
For satisfying the following conditions, two iterators begin and end form an iterator range:
- They point to an element in the same container, or a position after the last element of the container
- We can reach end by repeatedly incrementing begin, that is, end is not before begin
9.4
#include<iostream>
#include<vector>
using namespace std;
typedef vector<int>::iterator veci;
bool find(veci A, veci B, int c) {
while(A != B) {
if(*A == c) return true;
++A;
}
return false;
}
int main()
{
vector<int> vec = {
9, 9, 8, 2, 4, 4, 3, 5, 3};
for(int i = 0; i < 10; ++i) {
if(find(vec.begin(), vec.end(), i)) cout << i << " is in vec.\n";
else cout << i << " is not in vec\n";
}
return 0;
}
9.5
#include<iostream>
#include<vector>
using namespace std;
typedef vector<int>::iterator veci;
veci find(veci A, veci B, int c) {
while(A != B) {
if(*A == c) return A;
++A;
}
return B;
}
int main()
{
vector<int> vec = {
9, 9, 8, 2, 4, 4, 3, 5, 3};
for(int i = 0; i < 10; ++i) {
auto it = find(vec.begin(), vec.end(), i);
if(it == vec.end()) cout << i << " is not in vec.\n";
else cout << *it << " is in vec\n";
}
return 0;
}
9.6
list<int> lst1;
list<int>::iterator iter1 = lst1.begin(),
iter2 = lst1.end();
while(iter1 < iter2) /* ... */
The arithmetic operators of iterators can only be applied to iterators of string, vector, deque, and array.
Therefore need to
while(iter1 < iter2)
change into:
while(iter1 != iter2)