• 数组中元素查找和find()函数


    1、字符数组查找

    #include <stdlib.h>
    #include <stdio.h>
    #include <math.h>
    #include <cstring>
    #include <algorithm>  
    #include <iostream>
    using namespace std;
    int main()
    {
    string str;
    int n;
    char ch;
    cin>>str;
    getchar();
    scanf("%c",&ch);
    cout<<str.find(ch)+1;
      return 0;
    }
    


    2、整型数组元素查找

    (1)最一般的查找方式,直接循环查找  

    (2)使用vector查找

           

    #include <iostream>
    #include <vector>
    #include <cstdio>
    #include <algorithm>
    using namespace std;
    int main(){
            int x,n;
    		scanf("%d",&n);
            vector<int> v;//要查找的元素,类型要与vector<>类型一致
            for(int i=0;i<n;i++)
              {
              	
              	scanf("%d",&x);
                v.push_back(x);
    		  }
    		 scanf("%d",&x); 
           vector<int>::iterator iter=std::find(v.begin(),v.end(),x);//返回的是一个迭代器指针
            if(iter==v.end())
                cout<<-1;
            else               //注意迭代器指针输出元素的方式和distance用法
                cout<< distance(v.begin(), iter)+1 ;
            return 0;
    }

     直接使用int类型的数组只能返回数组里有没有该元素,所以若查找具体位置需要用vector,如:

    #include <iostream>
    #include <vector>
    #include <algorithm>//注意要包含该头文件
    using namespace std;
    int main()
    {
        int nums[] = { 3, 1, 4, 1, 5, 9 };
        int* result = find( nums , nums + 5,3 );
        if( result == nums + 5 ) 
            cout<< "Did not find any number matching " << endl;
        else
             cout<< "Found a matching number: " << *result << endl;
        return 0;
    }


  • 相关阅读:
    web服务器IIS 64位无法调用32位驱动问题
    asp.net临时文件的重定向
    手机归属地演示代码
    空气质量监测演示代码
    地图坐标服务
    车辆违章查询演示代码
    Python第二天
    python第七天
    python操作MongoDB
    Python第一天
  • 原文地址:https://www.cnblogs.com/zswbky/p/5432023.html
Copyright © 2020-2023  润新知