posts - 1,  comments - 0,  trackbacks - 0
find()函数的伪代码如下:
template<class InputIterator, class T>
  InputIterator find ( InputIterator first, InputIterator last, const T& value )
  {
    for ( ;first!=last; first++) if ( *first==value ) break;
    return first;
  }
一般第一个参数是迭代器的起始位置,第二参数是迭代器的结束位置,第三个参数是要查找的参数。当然参数也可以是数组名或者指针。如下所示:

 

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

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

  // pointer to array element:
  p = find(myints,myints+4,30);
  ++p;
  cout << "The element following 30 is " << *p << endl;

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

  // iterator to vector element:
  it = find (myvector.begin(), myvector.end(), 30);
  ++it;
  cout << "The element following 30 is " << *it << endl;

  return 0;
}

接收函数返回值的是一个地址值或者同类型的迭代器。区分string类的find()函数。

通过it==myvector.end()来判断是否找到此值,相等说明没找到。
补充一例:

泛型算法find的使用(必须包含头文件algorithm)

 

2011-01-13 17:11

#include<iostream>
#include <algorithm>//使用泛型算法必须包含头文件algorithm
#include<vector>
#include<string>
using namespace std;
int main()
{
 vector<int> ivec;
 while(true)
 {
  cout<<"continue?no(0) yes-enter an int value(not 0):"<<endl;
  int val;
  cin>>val;
  if(val==0)
   break;
  else
   ivec.push_back(val);
 }
 cout<<"please enter int value what you want to find:"<<endl;
 int ival;
 cin>>ival;
 vector<int>::const_iterator cit=find(ivec.begin(),ivec.end(),ival);//find算法是在algorithm中定义的
 cout<<"what you find "<<ival<<(cit==ivec.end()? " is not find" : " found")<<endl;
 return 0;
}


删除容器的操作可见C++primer第四版的9.3.7。

posted on 2012-04-04 13:23 愤怒的考拉 阅读(183) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航:
 
<2024年6月>
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456

常用链接

留言簿

随笔档案

文章档案

搜索

  •  

最新评论