如何查询vector中是否有某元素

#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!
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YMWM_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值