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指向key,second指向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;
}