第九章课后习题部分答案
《顺序容器》
练习9.5
#include
using namespace std;
typedef vector<int>::const_iterator it;
bool find(it first, it last, const int val) {
while (first != last && *first != val) {
++first;
}
return first != last;
}
int main() {
vector<int> v = {1, 2, 3, 4, 5, 7};
cout << find(v.cbegin(), v.cend(), 5) << endl;
cout << find(v.cbegin(), v.cend(), 6) << endl;
return 0;
}
练习9.6
#include
using namespace std;
typedef vector<int>::const_iterator it;
it find(it first, it last, const int val) {
while (first != last && *first != val) {
++first;
}
return first;
}
int main() {
vector<int> v = {1, 2, 3, 4, 5, 7};
cout << (find(v.cbegin(), v.cend(), 6) == v.cend()) << endl;
cout << (find(v.cbegin(), v.cend(), 5) == v.cend()) << endl;
return 0;
}
练习9.7
int main() {
list<int> l1;
list<int>::iterator it1 = l1.begin(), it2 = l1.end();
while (it1 != it2) {
}
return 0;
}
练习9.10
int main() {
vector<int> v1;
const vector<int> v2;
vector<int>::iterator it1 = v1.begin();
vector<int>::const_iterator it2 = v2.begin();
vector<int>::const_iterator it3 = v1.cbegin();
vector<int>::const_iterator it4 = v2.cbegin();
return 0;
}
练习9.11
#include
using namespace std;
typedef vector<int> C;
void print(C& c) {
for (int v : c) {
cout << v << ' ';
}
cout << endl;
}
int main() {
C c1;
C c = {1, 2, 3};
C c2(c);
C c3 = c;
C c4{1, 2, 3};
C c5 = {1, 2, 3};
C c6(c.begin(), c.begin());
print(c);
print(c1);
print(c2);
print(c3);
print(c4);
print(c5);
print(c6);
return 0;
}
练习9.13
#include
#include
using namespace std;
template <typename T>
void print(T& v) {
for (auto& c : v) {
cout << c << ' ';
}
cout << endl;
}
int main() {
list<int> l = {1, 2, 3};
vector<double> vd(l.begin(), l.end());
vector<int> vt = {4, 5, 6};
vector<double> vd2(vt.begin(), vt.end());
print(l);
print(vd);
print(vt);
print(vd2);
return 0;
}
练习9.14
#include
#include
#include
using namespace std;
template <typename T>
void print(T& v) {
for (auto& c : v) {
cout << c << ' ';
}
cout << endl;
}
int main() {
list<char*> l = {"aaa", "bbb"};
vector<string> v(l.begin(), l.end());
print(l);
print(v);
vector<string> v2;
v2.assign(l.begin(), l.end());
print(v2);
return 0;
}
练习9.31
#include
#include
#include
using namespace std;
template <typename T>
void print(T& v) {
for (auto& c : v) {
cout << c << ' ';
}
cout << endl;
}
int main() {
list<int> l = {0, 1, 2, 3, 4};
auto it = l.begin();
print(l);
while (it != l.end()) {
if (*it & 1) {
it = l.insert(it, *it);
it++, it++;
} else {
it = l.erase(it);
}
}
print(l);
return 0;
}
练习9.38
int main() {
vector<int> v;
int n = 0;
while (cin >> n) {
v.clear();
for (int i = 1; i <= n; ++ i) {
v.push_back(i);
printf("size = %d cap = %d\n", v.size(), v.capacity());
}
}
return 0;
}