如何检查给定的 int 是否存在于数组中? [英] How can I check if given int exists in array?

查看:52
本文介绍了如何检查给定的 int 是否存在于数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有这个数组:

int myArray[] = { 3, 6, 8, 33 };

如何检查给定的变量 x 是否在其中?

How to check if given variable x is in it?

我是否必须编写自己的函数并循环数组,或者在现代 C++ 中是否有与 PHP 中的 in_array 等效的函数?

Do I have to write my own function and loop the array, or is there in modern c++ equivalent to in_array in PHP?

推荐答案

您可以使用 std::find 为此:

You can use std::find for this:

#include <algorithm> // for std::find
#include <iterator> // for std::begin, std::end

int main () 
{
  int a[] = {3, 6, 8, 33};
  int x = 8;
  bool exists = std::find(std::begin(a), std::end(a), x) != std::end(a);
}

std::find 返回一个迭代器到 x 的第一次出现,或者返回一个迭代器,如果 x未找到.

std::find returns an iterator to the first occurrence of x, or an iterator to one-past the end of the range if x is not found.

这篇关于如何检查给定的 int 是否存在于数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆