C++语法基础--泛型算法(generic algorithm)--find(),find_if()

来源:互联网 发布:淘宝客怎么注册买家 编辑:程序博客网 时间:2024/06/06 22:59
1.使用泛型算法必须包含algorithm头文件


2.大多数算法是通过遍历由两个迭代器标记的一段元素来实现其功能,典型情况下,算法在遍历一段元素范围时,操纵其中的每一个元素。


3.find()
  只要找到与给定值相等的元素,find就会返回指向该元素的迭代器
  原型:
   template <class InputIterator, class T>
   InputIterator find (InputIterator first, InputIterator last, const T& val);

 等效原理:
   template<class InputIterator, class T>
  InputIterator find (InputIterator first, InputIterator last, const T& val)
{
  while (first!=last) {
    if (*first==val) return first;
    ++first;
  }
  return last;
}

eg:
  int main(void)
{
   int myints[] = { 10, 20, 30 ,40 };
  int * p;

 // pointer to array element:
  p = find (myints,myints+4,30);
  ++p;
  cout << *p << '\n';//40

  vector<int> myvector (myints,myints+4);
  vector<int>::iterator it;

  // iterator to vector element:
  it = find (myvector.begin(), myvector.end(), 30);
  ++it;
  cout<< *it << '\n';//40

  return 0;
}




4.迭代算法和容器绑定起来
  要求:
  *遍历容器。
  *元素类型支持==操作符,否则需要额外提供比较函数
 
 eg:如果class A 没有重载==操作符,则程序编译失败
  class A
{
public:
A(int i):x(i){}
void f(){cout<<x<<endl;}
    bool operator==(A b) const

return x==b.x;
     }
private:
int x;
};


int main(void)
{
  A a(1),b(2),c(3);
  vector<A> myvector ;
  myvector.push_back(a);
  myvector.push_back(b);
  myvector.push_back(c);
  vector<A>::iterator it;

  // iterator to vector element:
  it = find (myvector.begin(), myvector.end(), b);
  
  it->f();//2
  
   return 0;

}




4.find_if

   Returns an iterator to the first element in the range [first,last) for which pred returns true. 
   If no such element is found, the function returns last.
 

 原型:
template <class InputIterator, class UnaryPredicate>
   InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);


该算法等效于:
 template<class InputIterator, class UnaryPredicate>
  InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred)
{
  while (first!=last) {
    if (pred(*first)) return first;
    ++first;
  }
  return last;
}


 解析:
  first, last:
            Input iterators to the initial and final positions in a sequence. 
  pred       :
             Unary function that accepts an element in the range as argument and returns a value convertible to bool.



 Example:


bool IsEven (int i) {
  return ((i%2)==0);
}


int main () 

{
   int arr[]={1,2,3,2,1};
  vector<int> myvector(arr,arr+5);
  vector<int>::iterator it ;
  it=std::find_if (myvector.begin(), myvector.end(), IsEven);
  cout << "The first Even value is " << *it << '\n';


  return 0;
}


Output:The first Even value is 2