#include <vector>
#include <algorithm>
vector<int> a;
//1 利用count
count(a.begin(), a.end(), x) == 1;//a中存在x
count(a.begin(), a.end(), x) == 0;//a中不存在x
//2 利用find
find(a.begin(), a.end(), x) != a.end();//a中存在x
find(a.begin(), a.end(), x) == a.end();//a中不存在x
//3 利用迭代器遍历
vetor<int>::iterator it = a.begin();
bool IsExist = false;
while(it != a.end())
{
if(*it == x)
{
IsExist = true;
break;
}
it++;
}
IsExist == true;//a中存在x
IsExist == false;//a中不存在x
//4 使用for循环遍历
bool IsExist = false;
for(int i = 0; i < a.size(); i++)
if(a[i] == x)
{
IsExist = true;
break;
}
IsExist == true;//a中存在x
IsExist == false;//a中不存在x
示例代码,
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void method1(vector<int> a, int x)
{
if(count(a.begin(), a.end(), x) == 1)
cout << "容器a中有" << x << "!" << " ";
else
cout << "容器a中没有" << x << "!" << " ";
}
void method2(vector<int> a, int x)
{
if(find(a.begin(), a.end(), x) != a.end())
cout << "容器a中有" << x << "!" << " ";
else
cout << "容器a中没有" << x << "!" << " ";
}
void method3(vector<int> a, int x)
{
vector<int>::iterator it = a.begin();
bool IsExist = false;
while(it != a.end())
{
if(*it == x)
{
IsExist = true;
break;
}
it++;
}
if(IsExist == true)
cout << "容器a中有" << x << "!" << " ";
else
cout << "容器a中没有" << x << "!" << " ";
}
void method4(vector<int> a, int x)
{
bool IsExist = false;
for(int i = 0; i < a.size(); i++)
if(a[i] == x)
{
IsExist = true;
break;
}
if(IsExist == true)
cout << "容器a中有" << x << "!" << " ";
else
cout << "容器a中没有" << x << "!" << " ";
}
int main()
{
vector<int> a = {1, 2, 3, 4, 5};
//1 利用count
cout << "1利用count: ";
method1(a, 1);
method1(a, 6);
cout << endl;
//2 利用find
cout << "2利用find: ";
method2(a, 1);
method2(a, 6);
cout << endl;
//3 利用迭代器遍历
cout << "3利用迭代器遍历: ";
method3(a, 1);
method3(a, 6);
cout << endl;
//4 使用for循环遍历
cout << "4使用for循环遍历: ";
method4(a, 1);
method4(a, 6);
return 0;
}
输出为,
1利用count: 容器a中有1! 容器a中没有6!
2利用find: 容器a中有1! 容器a中没有6!
3利用迭代器遍历: 容器a中有1! 容器a中没有6!
4使用for循环遍历: 容器a中有1! 容器a中没有6!