essential c++ book note 2 chapter 3
chapter 3 generic(普通,共有的) programming
1, arithmetic of pointers :
the use of template, note that find return a pointer
template <typename elemType> elemType *find(const elemType *array, int size, const elemType &value)
2, iterators
use generic algorithms #include<algorithm>
3, sequential containers : vector , list , dequeue
4, generic algorithms
binary_search() requires that the container be sorted
when copy one vector to another vector, we should first locate the size of new vector
vector<int> temp(vec.size());
copy(vec.begin(), vec.end(). temp.begin());
5, design a generic algorithm
one solution, replace with function call
vector<int> filter (const vector<int> &vec, int filter_value, bool (*pred)(int, int));
bool less_than(int v1, int v2){ return v1<v2 ? true : false; }
function objects
#include <functional> sort(vec.begin(), vec.end(), greater<int>()) // great<int>() is function object
function object adapters
vector<int> filter (const vector<int> &vec, int val, less<int> <) { find_if(tier, vec.end(), bind2nd(lt, val)); //bind second val to 2nd op, which means < val } //also we can use template template <typename InputIterator, typename OutputIterator, typename ElemType, typename Comp> OutputIterator filter( InputIterator first, InputIterator last, OutputIterator at, const ElemType &val, Comp pred) { find_if(first, last, bind2nd(red, val)) != last; } main() { //test filter(vec.begin(), vec,end(), vec2.begin(), elem_size, great<int>()); //out put num which is > than elem_size }
6, use map
= operator actually equals insert()
7 iterator inserters
to prevent heap leak, we should set the size of the containers beforehand
OR use inserters
unique_copy(vec.begin(), vec.end(), back_inserter(res_vec)); //since vector only have push_back() method
8, iostream iterators
it provides us another way to implement input and output
#include <iterator> istream_iterator <string> is(cin); //use stdin as input istream_iterator <string> eof; copy(is, eof, back_inserter(vex)); ofstream out_file("1.txt"); //we can also use file as input ostream_iterator <string> os(out_file, " "); copy(vex.begin(), vex.end(), os);