【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

原文地址:https://www.cnblogs.com/wwj321/p/12616456.html