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

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

问题描述

例如,我有这样的数组:

For example, I have this array:

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

如何检查是否给定的变量x是吧?

How to check if given variable x is in it?

我必须写我自己的函数和循环数组,或者是有现代C ++相当于 in_array 在PHP?

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 ::找到 此:

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 ::找到返回一个迭代器的 X ,第一次出现或一个迭代器一过去范围到底是 X 是找不到的。

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

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

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