学而思的老师工资待遇:STL库中find函数

来源:百度文库 编辑:偶看新闻 时间:2024/04/28 00:50:46

接触STL不多,但每当写程序的时候,会先想到用它,还算个好习惯吧,毕竟自己写的链表之类的没那么好。

如何使用STL进行查找?通用算法find()和find_if()可以做这些。就象for_each(), count(), count_if()一样,这些算法也使用iterator范围,这个范围指出一个list或任意其他容器中的一部分来处理。通常首iterator指着开始的位置,次iterator指着停止处理的地方。由次iterator指出的元素不被处理。
这是find()如何工作:

/*
|| How to find things in an STL list
*/
#include<
string>
#include <
list>
#include <algorithm>

int main (void){
    list
Fruit;
    list
::iterator FruitIterator;

   Fruit.push_back("Apple");
   Fruit.push_back("Pineapple");
   Fruit.push_back("Star Apple");

   FruitIterator = find (Fruit.begin(), Fruit.end(),"Pineapple");
 
    if
(FruitIterator == Fruit.end()) {
       cout << "Fruit not found in list" << endl;
    }
    else
{
       
cout<< *FruitIterator <    }
}

输出是:

Pineapple

如果没有找到指出的对象,就会返回Fruit.end()的值,要是找到了就返回一个指着找到的对象的iterator。

/*值得注意的是,这里find函数的最后一个参数,我认为需要是简单简单类型的内容,或者是缺醒类型,如string,int, char, double,float等,如果你想用一个自定义类型的数据作为查找依据则会出错。

如,有这样的数据结构:

structMyType

{

  int a,b;

}

MyType*mt;

mt = new MyType;

mt->a = 1;

mt->b = 2;

list mList;

find(mList.begin(), mList.end(), *mt);

这里find函数是不能完成查询的,最简单的原因就是它无法知道通过对比MyType的哪项完成查询。

所以,在这样的情况下有两种选择,一种是写一个查找条件函数,利用find_if(),另一种就是自己写查询函数。当然推荐第一种。*/

--------------------------------------------------------------------------------

使用STL通用算法find_if()在list中搜索对象


这是find()的一个更强大的版本。这个例子演示了find_if(),它接收一个函数对象的参数作为参数,并使用它来做更复杂的评价对象是否和给出的查找条件相付。
假设我们的list中有一些按年代排列的包含了事件和日期的记录。我们希望找出发生在1997年的事件。

/*
|| How to find things in an STL list MkII
*/

#include
#include
#include

 
class EventIsIn1997 {
public:

    bool
operator () (string&EventRecord) {
       // year field is at position 12 for 4characters in EventRecord
       return
EventRecord.substr(12,4)=="1997";
    }
};
 
int
main (void) {
    list
Events;
 
    // string positions0123456789012345678901234567890123456789012345
   Events.push_back("07 January 1995 Draft plan of houseprepared");
   Events.push_back("07 February 1996 Detailed plan of houseprepared");
   Events.push_back("10 January 1997 Client agrees to job");
   Events.push_back("15 January 1997 Builder starts work onbedroom");
   Events.push_back("30 April 1997 Builder finishes work");
 
    list::iterator EventIterator =find_if (Events.begin(), Events.end(), EventIsIn1997());
 
    // find_if completes the first time EventIsIn1997()()returns true
    // for anyobject. It returns an iterator to that object which we
    // candereference to get the object, or if EventIsIn1997()() never
    // returnedtrue, find_if returns end()

    if
(EventIterator==Events.end()) {
       
cout <<"Event not found in list" << endl;
    }
   
else{
       
cout<<*EventIterator << endl;
    }
}

这是程序的输出:

10 January 1997 Client agrees to job

--------------------------------------------------------------------------------

使用STL通用算法search在list中找一个序列
一些字符在STL容器中很好处理,让我们看一看一个难处理的字符序列。我们将定义一个list来放字符。
list Characters;

现在我们有了一个字符序列,它不用任何帮助就知道然后管理内存。它知道它是从哪里开始、到哪里结束。它非常有用。我不知道我是否说过以null结尾的字符数组。

让我们加入一些我们喜欢的字符到这个list中:

Characters.push_back('\0');
Characters.push_back('\0');
Characters.push_back('1');
Characters.push_back('2');


我们将得到多少个空字符呢?


int NumberOfNullCharacters(0);
count(Characters.begin(), Characters.end(), '\0',NumberOfNullCharacters);
cout << "We have " <
让我们找字符'1'

listr>::iterator Iter;
Iter = find(Characters.begin(), Characters.end(), '1');
cout << "We found " << *Iter << endl;

这个例子演示了STL容器允许你以更标准的方法来处理空字符。现在让我们用STL的search算法来搜索容器中的两个null。
就象你猜的一样,STL通用算法search()用来搜索一个容器,但是是搜索一个元素串,不象find()和find_if()只搜索单个的元素。

/*
|| How to use the search algorithm in an STL list
*/

#include
#include
#include

 
int main (void){
 
    list
<char> TargetCharacters;
    list<
char>ListOfCharacters;
 
   TargetCharacters.push_back('\0');
   TargetCharacters.push_back('\0');
 
   ListOfCharacters.push_back('1');
   ListOfCharacters.push_back('2');
   ListOfCharacters.push_back('\0');
   ListOfCharacters.push_back('\0');
 
    list<char>::iterator PositionOfNulls =search(ListOfCharacters.begin(), ListOfCharacters.end(),TargetCharacters.begin(), TargetCharacters.end());
 
    if (PositionOfNulls!=ListOfCharacters.end())
       
cout<< "We found the nulls"<< endl;
}

The output of the program will be 这是程序的输出:

We found the nulls

search算法在一个序列中找另一个序列的第一次出现的位置。在这个例子里我们在ListOfCharacters中找TargetCharacters这个序列的第一次出现,TargetCharacters是包含两个null字符的序列。
search的参数是两个指着查找目标的iterator和两个指着搜索范围的iterators。因此我们我们在整个的ListOfCharacters的范围内查找TargetCharacters这个list的整个序列。

如果TargetCharacters被发现,search就会返回一个指着ListOfCharacters中序列匹配的第一个字符的iterator。如果没有找到匹配项,search返回ListOfCharacters.end()的值。

用C++的stl库,相信大家都有用vector的经历,毕竟vector支持直接下标方式取数据的确方便很多。

但是vector默认是不提供find方法的,所以我们在查找的时候,通常这样写代码:

vector<int> vec;
for(unsigned int i = 0;i{
    if(vec[i]==xxx)
    {
        break;
    }
}

并不是说提供不了,而是stl库中实际上已经有通用的find函数(不止find……)

可以看一下下面的代码:

int main(int argc,char* argv[])
{
    vector<int> vec;
    vec.push_back(123);
    vec.push_back(456);
    vector<int>::iterator findit = find(vec.begin(),vec.end(),123);
    //vector::iterator findit = find(vec.begin(),vec.end(),111);
    if(findit==vec.end())
    {
        printf("no find\n");
    }
    else
    {
        printf("find[%d]\n",*findit);
    }
    return 0;
}

这样的写法会不会简单很多呢?
需要说明的是,虽然这个通用的find方法也是可以用在map,set等上面的,但是效率会比容器内部的find方法慢很多,所以,除非容器实在是没有提供find方法,否则还是建议不要用公共的这一种。

另外,作为题外话,我们需要注意一下vector的删除(erase)操作。由于vector需要能以下标方式取数据,所以必须时刻保证连续的存储空间,对应于实现上,即,当删除vector中间的一个成员时,这个成员后面的所有成员,会以原顺序向前全部拷贝过来。有兴趣的朋友,可以用这个例子测试一下。
这里起码告诉了我们两件事:

1.vector中一个成员被删除,会导致后面的成员进行copy和析构操作。
2.vector不适合做有大量插入删除操作的容器,因为拷贝内存本身浪费很大

OK,到此为止啦~