zoukankan      html  css  js  c++  java
  • STL学习之find系列函数

    这里先介绍find, find_if, find_first_of,三个函数。其余的以后再更新。

    一、std::find()

    用法:find(first, end, value);

    返回区间[first,end)中第一个值等于value的元素位置;若未找到,返回end。函数返回的是迭代器或指针,即位置信息。

    参考代码main(),查找findvalue的值

    二、std::find_if()

    用法:find_if(first, end, bool pred);

    返回区间[first,end)中使一元判断式pred为true的第一个元素位置;若未找到,返回end。

    参考代码main(),test_find_if();查找第一个被5整除的数,pred写成bool函数

    三、std::find_first_of()

    用法:find_first_of(first1, end1, first2, end2);

     返回第一个区间迭代器位置,满足第一个区间[first1,end1)中的元素第一次出现在第二个区间[first2,end2)中。

    通俗就是说顺序从第一个区间[first1,end1)中取一个元素,在第二个区间中找有没有相同的元素,如果有就返回第一个区间中元素位置;未找到则继续

    用第一个区间的下一个元素在第二个区间找。

    因此只要保证两个区间内的元素可以==即可,不用管装元素的容器形式。下面的例子我第一个区间用的vector、而第二个区间是list也是可以的。

    参考代码main(),test_find_first_of();查找vector中第一次出现在list的元素。

    代码示例:

     1 bool divbyfive(int x)
     2 {
     3     return x%5 ? 0 : 1;
     4 }
     5 
     6 void test_find_if(vector<int> vec)
     7 {
     8     vector<int>::iterator vec_it;
     9     vec_it=find_if(vec.begin(),vec.end(),divbyfive);
    10     if (vec_it!=vec.end())
    11     {
    12         cout<<"满足判断函数的数为: "<<*vec_it<<"位置在"<<vec_it-vec.begin()<<endl;
    13     } 
    14     else
    15     {cout<<"未找到满足判断函数的数"<<endl;
    16     }
    17     return;
    18 }
    19 
    20 void test_find_first_of(vector<int> vec)
    21 {
    22     list<int> list2;
    23     for (int i=20;i>5;i--)
    24     {
    25         list2.push_back(i);
    26     }
    27     vector<int>::iterator vec_it;
    28     vec_it=find_first_of(vec.begin(),vec.end(),list2.begin(),list2.end());
    29     if (vec_it!=vec.end())
    30     {
    31         cout<<"第一次出现在第二个容器的元素为: "<<*vec_it<<"位置在: "<<vec_it-vec.begin()<<endl;
    32     } 
    33     else
    34     {
    35         cout<<"两个容器没有相同元素"<<endl;
    36     }
    37 }
    38 
    39 int main()
    40 {
    41     vector<int> vec;
    42     int findvalue=11;
    43     for (int i=1;i<11;i++)
    44     {
    45         vec.push_back(i);
    46     }
    47     vector<int>::iterator vec_it;
    48     vec_it=find(vec.begin(),vec.end(),findvalue);
    49     if (vec_it!=vec.end())
    50     {
    51         cout<<findvalue<<" position is "<<distance(vec.begin(),vec_it)<<endl;
    52     }
    53     else
    54         cout<<findvalue<<"is not found"<<endl;
    55 
    56     test_find_if(vec);
    57     test_find_first_of(vec);
    58     return 0;
    59 }

    参考:http://www.cnblogs.com/heyonggang/p/3241789.html

  • 相关阅读:
    Python动态展示遗传算法求解TSP旅行商问题
    MOEAD算法中均匀权向量的实现---Python
    HDU 5294 多校第一场1007题 最短路+最小割
    POJ 3261 Milk Patterns sa+二分
    HDU 4292 FOOD 2012 ACM/ICPC Asia Regional Chengdu Online
    CodeForces 201A Clear Symmetry
    POJ 1679 The Unique MST 确定MST是否唯一
    POJ 3268 Silver Cow Party 最短路 基础题
    POJ 2139 SIx Degrees of Cowvin Bacon 最短路 水題
    POJ2229 Sumsets 基礎DP
  • 原文地址:https://www.cnblogs.com/chenzhefan/p/5649429.html
Copyright © 2011-2022 走看看