zoukankan      html  css  js  c++  java
  • 【C++】使用find函数快速定位元素

    当有了STL,你还在用遍历的土方法定位元素吗?

    今天就来介绍一下,如何使用algorithm库里的find函数快速定位数组或向量中的元素。

    首先当然要包含头文件:

     #include <algorithm>
    

    它的基本语法是这样的:

    iterator find( iterator start, iterator end, const TYPE& val );
    

    参数就是要查找的范围的起始和结束位置(注意区间是左闭右开的)以及要查找的值。

    比如查找向量中的值:

    int num_to_find = 3;
    vector<int> v1;
    for (int i = 0; i < 10; i++)
    {
        v1.push_back(i);
    }
    vector<int>::iterator result;
    result = find(v1.begin(), v1.end(), num_to_find);
    if (result == v1.end())
    {
        cout << "Did not find any element matching " << num_to_find << endl;
    }
    else
    {
        cout << "Found a matching element: " << *result << endl;
    }
    

    又比如查找一个静态数组中的值:

    int nums[] = { 3, 1, 4, 1, 5, 9 }; 
    int num_to_find = 3; 
    int start = 0; 
    int end = 2; 
    int* result = find(nums + start, nums + end, num_to_find);                 
    if (result == nums + end) { 
    	cout << "Did not find any number matching " << num_to_find << endl; 
    }
    else { 
    	cout << "Found a matching number: " << *result << endl; 
    }
    

    :记录以备忘

  • 相关阅读:
    Python基础07
    python基础06
    python基础05
    python基础04
    python基础03
    python基础02
    python组件之wtforms
    PythonWeb框架之Flask
    Linux下yum安装Redis
    在vuex的mutations中使用vue的小技巧
  • 原文地址:https://www.cnblogs.com/ben-future/p/find.html
Copyright © 2011-2022 走看看