C++:通过count和find判断vector中是否包含某个数据

vector本身没有提供可以检测某个数据是否在其中的成员方法,可以使用泛型方法count和find进行检查:

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

int main()
{
	vector<int> d{1, 2, 2, 2, 3, 4, 5};
	auto num = count(d.begin(), d.end(), 2);
	cout<<"has 2 for "<<num<<" times"<<endl;
	auto ifFind = find(d.begin(), d.end(), 3);
	if(ifFind != d.end())
	{
		cout<<"find data 3"<<endl;
	}
	return 0;
}

运行程序输出:

has 2 for 3 times

find data 3

需要说明的是,count需要计数,所以会遍历整个vector,所以效率会低一些。 

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-05 14:50:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-05 14:50:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-02-05 14:50:01       87 阅读
  4. Python语言-面向对象

    2024-02-05 14:50:01       96 阅读

热门阅读

  1. 正则表达式

    2024-02-05 14:50:01       42 阅读
  2. WSL和Ubuntu编译IJKPlayer

    2024-02-05 14:50:01       44 阅读
  3. 前端实现数组的去重

    2024-02-05 14:50:01       54 阅读
  4. 排序刷题3

    2024-02-05 14:50:01       56 阅读
  5. 【Ubuntu】安装filebeat

    2024-02-05 14:50:01       55 阅读
  6. ubuntu 安装 ffmpeg 6.0

    2024-02-05 14:50:01       57 阅读
  7. 蓝桥杯典型真题分析详解--编程思维--日期统计

    2024-02-05 14:50:01       44 阅读
  8. ASR 概述

    2024-02-05 14:50:01       47 阅读
  9. SQL--DDL

    SQL--DDL

    2024-02-05 14:50:01      49 阅读
  10. MySQL的DDL语言

    2024-02-05 14:50:01       51 阅读