essential c++ book note 2 chapter 3

本文深入探讨了通用编程概念,包括指针算术、迭代器使用、泛型算法如binary_search()的应用,以及如何设计通用算法。同时,文章介绍了如何使用vector、list和deque等顺序容器,并展示了如何通过函数对象和迭代器插入器来增强代码的灵活性和效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值