Essential c++ the third part

essential c++

=======================第三章复习=========================
- 泛型指针的应用 (genetic iterator)
为了将elemtype拓展到更宽泛的数据类型的范围,而不只仅限于vector和array,更可以使用于list,书中提出可以使用genetic iterator,让使用vector却不以vector的方式呈现,使用array却不以array的下标索引。具体操作方式是传入两个iterator指针,一个指向数据的开始,另一个指向结尾,(分别可以由vec.begin(),vec.end()函数实现,返回值均为iterator)。通过对first依次遍历从而遍历整个数组(或list)。具体实现如下:

#include<iostream>
#include<vector>
#include<list>
using namespace std;
//using iterator to make a genric algorithm
template <typename iteratortype,typename elemtype>
iteratortype find(iteratortype first,iteratortype last,
                const elemtype &value)
{
    for(;first!=last;first++)
    {
        if(*first==value)
        {
            return first;
        }   
    }
    return last;
}
int main(void)
{
    int m[10]={2,3,5,6,73,33,323,564,567,3};
    vector<int>vec(m,m+10);
    int n=333;
    //vector elem find 
    vector<int>::iterator p=find(vec.begin(),vec.end(),n);
    if(p!=vec.end())
    {
        cout<<"exist "<<*p<<endl;
    }
    //int elem find
    int *q=find(m,m+10,323);
    if(q!=m+10)
    {
        cout<<"exist "<<*q<<endl;
    }
    //list elem find
    list<int>ilist(m,m+10);
    list<int>::iterator iter;
    iter=find(ilist.begin(),ilist.end(),33);
    if(iter!=ilist.end())
    {
        cout<<"exist "<<*iter<<endl;
    }
}
  • 函数对象 (function object)
    所谓function object实际是某种类的实例对象,该类对function call做了重载操作,因而可以作为一般函数使用,目前对我比较有用的是less(),greater(),可以作为sort的parameter。同时书上还提到了function object adapter。因为本身less()等为二元运算符,而我们可以将一个数绑定至less()的parameter上从而将less()转化为一元运算符。标准库提供了两个binder adapter (绑定适配器),其中bind1st将指定值绑定☞第一操作数,bind2nd同理。
  • 使用map和set
    set是由一群key组成,而map则由key和value两部分组成,一个很好的例子是用map记录一篇文章中出现各个单词的个数,set则用来匹配并忽略一些不需要的单词。其中map中有一些要提及的地方
    • map中有两个对象,first指向keysecond指向value
    • 查询需要使用find(),而不能直接if(word[“abc”]),因为如果没有abc这个key那么会自动加入abc这个key并让其value为0.
      试验代码如下:
#include<map>
#include<string>
#include<iostream>
#include<cstring>
using namespace std;
int main(void)
{
    string tword;
    map<string,int>words;
    while(cin>>tword)
    {
        words[tword]++;
    }
    //display the map
    map<string,int>::iterator iter=words.begin();
    for(;iter!=words.end();iter++)
    {
        cout<<"key:"<<iter->first
        <<" value:"<<iter->second<<endl;
    }
    //find the key (using find(),not same as find() before,its return is a iterator)
    map<string,int>::iterator it;
    it=words.find("chenze");
    if(it!=words.end())
    {
        cout<<"find the key "<<it->first<<
        " and its appearance is"<<it->second<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值