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)

in function, *(array+2) means adds 2 of the size of the elemType being addressed.

 

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);

 

原文链接: https://www.cnblogs.com/ggppwx/archive/2011/01/07/1929870.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    essential c++ book note 2 chapter 3

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/19767

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月7日 下午9:06
下一篇 2023年2月7日 下午9:06

相关推荐