16.4
template<typename itator, typename type>
itator find(itator it, type f)
{
while (*it != f)
it++;
return it;
}
#include <iostream>
#include <vector>
#include <list>
#include "head.h"
using namespace std;
int main()
{
vector<int> vec = { 2,3,4,5,6,7,8, };
list<string> lst = { "it","is","a","test", };
cout << *find(vec.cbegin(), 5) << endl;
cout << *find(lst.cbegin(), "is") << endl;
return 0;
}
16.5
template<typename type, unsigned N>
void print(const type(&arr)[N])
{
for (auto i : arr)
std::cout << i << " ";
std::cout << std::endl;
}
#include <iostream>
#include "head.h"
using namespace std;
int main()
{
int i[20] = { 2,3,4,5,6,7 };
::print(i);
double b[30] = { 2.2, 3.3, 5.6, 6.7, 7.9, };
::print(b);
string s[10] = { "it","is","a","test", };
::print(s);
return 0;
}
16.6
template<typename T, unsigned N>
T* begin_array(T (&arr) [N])
{
return arr;
}
template<typename T, unsigned N>
T* end_array(T (&arr) [N])
{
return (begin_array(arr) + N);
}
#include <iostream>
#include "head.h"
using namespace std;
int main()
{
int i[6] = { 2,3,4,5,6,7 };
cout << *begin_array(i) << "\t" << *(end_array(i) - 1) << endl;
double b[5] = { 2.2, 3.3, 5.6, 6.7, 7.9, };
cout << *begin_array(b) << "\t" << *(end_array(b) - 1) << endl;
string s[4] = { "it","is","a","test", };
cout << *begin_array(s) << "\t" << *(end_array(s) - 1) << endl;
return 0;
}
16.7
template<typename T, unsigned N>
constexpr unsigned size(T(&arr)[N])
{
return N;
}
#include <iostream>
#include "head.h"
using namespace std;
int main()
{
int i[6] = { 2,3,4,5,6,7 };
cout << size(i) << endl;
double b[5] = { 2.2, 3.3, 5.6, 6.7, 7.9, };
cout << size(b) << endl;
string s[4] = { "it","is","a","test", };
cout << size(s) << endl;
return 0;
}
16.19 & 16.20
#include <iostream>
#include <vector>
#include <list>
#include "head.h"
using namespace std;
template<typename C>
void print(const C& c)
{
for (typename C::size_type i = 0; i != c.size(); ++i)
cout << c[i] << " ";
}
int main()
{
vector<int> vec{ 1,2,3,4,5,6,7 };
print(vec);
return 0;
}
16.21
class DebugDelete {
public:
DebugDelete(ostream& s = cerr) :os(s) {}
template<typename T>void operator()(T*p)const
{
os << "deleting unique_ptr" << endl;
delete p;
}
private:
ostream& os;
};
16.24
#include <iostream>
#include <vector>
#include "head.h"
using namespace std;
template<typename T> class Blob {
public:
template<typename It> Blob(It b, It e);
shared_ptr<vector<T>> data;
};
template<typename T>
template<typename It>
Blob<T>::Blob(It b, It e) : data(make_shared<vector<T>>(b, e)) {}
int main()
{
vector<int> vec{ 1,2,3,4,5,6,7,8 };
Blob<int> b(vec.begin(), vec.end());
return 0;
}