C++ 查找数组或者容器元素是否存在(find)
代码如下:
#include <iostream> // cout
#include <algorithm> // find
#include <vector> // vector
#include <typeinfo>
using namespace std;
int main () {
// using find with array and pointer:
int myints[] = { 10, 20, 30, 40 };
int * p;
p = find (myints, myints+4, 30); //返回查找到的元素的物理地址
cout<<p<<"\n";
if (p != myints+4)
cout << "Element found in myints: " << *p << '\n';
else
cout << "Element not found in myints\n";
// using find with vector and iterator:
vector<int> myvector (myints,myints+4);
vector<int>::iterator it;
it = find (myvector.begin(), myvector.end(), 30);
cout<<typeid(it).name()<<"\n";
if (it != myvector.end())
cout << "Element found in myvector: " << *it << '\n';
else
cout << "Element not found in myvector\n";
return 0;
}
本文介绍了如何使用C++标准库中的find函数来查找数组和vector容器中的元素。通过两个实例展示了find函数的用法:一是针对整型数组,二是针对vector容器。每个示例都包括了查找成功和失败的情况,并输出相应的信息。
597

被折叠的 条评论
为什么被折叠?



