检查在数组c ++中是否找到元素 [英] Check if element found in array c++

查看:198
本文介绍了检查在数组c ++中是否找到元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查我的数组是否有我正在寻找的元素?



在Java中,我会这样做:

  Foo someObject = new Foo(someParameter); 
Foo foo;
//搜索Foo [] arr
for(int i = 0; i if arr [i] .equals(someObject)
foo = arr [i];
}
if(foo == null)
System.out.println(Not found!);
else
System.out.println(Found!);

但是在C ++中我不认为我可以搜索一个Object是否为空在C ++中,你将使用 std :: find $ c>,并检查结果指针是否指向范围的结尾,如下所示:

  Foo array [10] ; 
... //在这里初始化数组
Foo * foo = std :: find(std :: begin(array),std :: end(array),someObject);
//当没有找到元素时,std :: find返回范围的结束
if(foo!= std :: end(array)){
cerr< Found at position<< std :: distance(array,foo)<< endl;
} else {
cerr<< 未找到<< endl;
}


How can I check if my array has an element I'm looking for?

In Java, I would do something like this:

Foo someObject = new Foo(someParameter);
Foo foo;
//search through Foo[] arr
for(int i = 0; i < arr.length; i++){
  if arr[i].equals(someObject)
    foo = arr[i];
}
if (foo == null)
  System.out.println("Not found!");
else
  System.out.println("Found!");

But in C++ I don't think I'm allowed to search if an Object is null so what would be the C++ solution?

解决方案

In C++ you would use std::find, and check if the resultant pointer points to the end of the range, like this:

Foo array[10];
... // Init the array here
Foo *foo = std::find(std::begin(array), std::end(array), someObject);
// When the element is not found, std::find returns the end of the range
if (foo != std::end(array)) {
    cerr << "Found at position " << std::distance(array, foo) << endl;
} else {
    cerr << "Not found" << endl;
}

这篇关于检查在数组c ++中是否找到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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