zoukankan      html  css  js  c++  java
  • 【C++】find函数的两种不同类型

    find

    主要有两种find。
    第一种为C++头文件中的函数,这种函数find格式如下:

    find(start,end,val);
    

    如果查找到了,会返回元素的引用或者指针,而不是返回下标,因为为了兼顾不同的数据结构,可能有的不是按照地址顺序存储的。

    //容器写法:
    find(a.begin(),a.end(),val);           //如果查找失败返回a.end()
    //数组
    find(a,a+lengh,val);
    

    第二种为容器的成员函数
    例如string ,返回的为下标值。若查找失败,则返回string::npos

    string s1("hello world");
    string s2("he");
    //查找第一次字符串出现的位置
    int index=s1.find(s2);
    //查找x开始第一次目标字符串出现的位置
    int ind=s1.find(s2,2);
    

    容器vector未定义find函数,map,set等因为不是顺序结构存储,所以返回的是迭代器。若查找失败返回a.end()

    如题:

    #include <iostream>
    #include <functional>
    using namespace std;
    int main()
    { 
        int A[5] = {5,3,1,4,2} ;
        int *location ;
        int value ;
        cin >> value;
        ______________       //待填空
        if (location != A + 5)
            cout << value << "是第"
                 << (location-A)+1 << "个元素" << endl;
        else
            cout << "error" << endl;
        return 0;
    }
    

    程序的功能是在A数组中查找值等于value的元素,请为横线处选择合适的程序( )

    A
    for(int i=0;i<5;i++)
      if(A[i]==value)
        location=&A[i];
    
    B
     for(int i=0;i<5;i++)
       if(A[i]==value)
         location=i;
    
    C
     location = find(A, A + 5, value) ;
    
    D
     for(int i=0;i<5;i++)
       if(A[i]==value)
         location=A[i];
    

    答案:A、C

  • 相关阅读:
    背包问题
    计蒜客lev3
    线段树BIT操作总结
    图论题收集
    Codeforces Round #607 (Div. 2) 训练总结及A-F题解
    2-sat 学习笔记
    洛谷 P3338 【ZJOI2014】力/BZOJ 3527 力 题解
    $noi.ac$ #51 array 题解
    洛谷 P3292 【SCOI2016】幸运数字/BZOJ 4568 幸运数字 题解
    洛谷 P5283 【十二省联考2019】异或粽子 题解
  • 原文地址:https://www.cnblogs.com/wwj321/p/12616456.html
Copyright © 2011-2022 走看看