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

  • 相关阅读:
    多多挣钱,多多攒钱。
    平安鸿运英才少儿教育金保障计划
    沙河订奶
    排序算法--参考
    《程序设计基础》考试大纲 复习-C语言
    There is no Action mapped for namespace [/demo1] and action name [doLogin] associated with context path [/SSO_same_domain]
    Android报错 The connection to adb is down, and a severe error has occured.
    解析库beautifulsoup
    request模块使用
    爬虫基本原理
  • 原文地址:https://www.cnblogs.com/chenzhefan/p/5649429.html
Copyright © 2011-2022 走看看