检查是否在数组 C++ 中找到元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19215027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if element found in array c++
提问by Omar Darwish
How can I check if my array has an element I'm looking for?
如何检查我的数组是否有我正在寻找的元素?
In Java, I would do something like this:
在 Java 中,我会做这样的事情:
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?
但是在 C++ 中,我认为我不允许搜索对象是否为空,那么 C++ 解决方案是什么?
回答by dasblinkenlight
In C++ you would use std::find
, and check if the resultant pointer points to the end of the range, like this:
在 C++ 中,您将使用std::find
, 并检查结果指针是否指向范围的末尾,如下所示:
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;
}
回答by Kevin Grant
There are many ways...one is to use the std::find()
algorithm, e.g.
有很多方法......一种是使用std::find()
算法,例如
#include <algorithm>
int myArray[] = { 3, 2, 1, 0, 1, 2, 3 };
size_t myArraySize = sizeof(myArray) / sizeof(int);
int *end = myArray + myArraySize;
// find the value 0:
int *result = std::find(myArray, end, 0);
if (result != end) {
// found value at "result" pointer location...
}
回答by Rivasa
You would just do the same thing, looping through the array to search for the term you want. Of course if it's a sorted array this would be much faster, so something similar to prehaps:
您只需执行相同的操作,遍历数组以搜索您想要的术语。当然,如果它是一个排序数组,这会快得多,所以类似于 prehaps:
for(int i = 0; i < arraySize; i++){
if(array[i] == itemToFind){
break;
}
}
回答by Kemin Zhou
You can use old C-style programming to do the job. This will require little knowledge about C++. Good for beginners.
您可以使用旧的 C 风格编程来完成这项工作。这将需要很少的 C++ 知识。适合初学者。
For modern C++ language you usually accomplish this through lambda, function objects, ... or algorithm: find
, find_if
, any_of
, for_each
, or the new for (auto& v : container) { }
syntax. find
class algorithm takes more lines of code. You may also write you own template find
function for your particular need.
对于现代C ++语言中,你通常是通过拉姆达做到这一点,函数对象,...或算法:find
,find_if
,any_of
,for_each
,或新的for (auto& v : container) { }
语法。 find
类算法需要更多的代码行。您也可以find
为您的特定需要编写自己的模板函数。
Here is my sample code
这是我的示例代码
#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>
using namespace std;
/**
* This is old C-like style. It is mostly gong from
* modern C++ programming. You can still use this
* since you need to know very little about C++.
* @param storeSize you have to know the size of store
* How many elements are in the array.
* @return the index of the element in the array,
* if not found return -1
*/
int in_array(const int store[], const int storeSize, const int query) {
for (size_t i=0; i<storeSize; ++i) {
if (store[i] == query) {
return i;
}
}
return -1;
}
void testfind() {
int iarr[] = { 3, 6, 8, 33, 77, 63, 7, 11 };
// for beginners, it is good to practice a looping method
int query = 7;
if (in_array(iarr, 8, query) != -1) {
cout << query << " is in the array\n";
}
// using vector or list, ... any container in C++
vector<int> vecint{ 3, 6, 8, 33, 77, 63, 7, 11 };
auto it=find(vecint.begin(), vecint.end(), query);
cout << "using find()\n";
if (it != vecint.end()) {
cout << "found " << query << " in the container\n";
}
else {
cout << "your query: " << query << " is not inside the container\n";
}
using namespace std::placeholders;
// here the query variable is bound to the `equal_to` function
// object (defined in std)
cout << "using any_of\n";
if (any_of(vecint.begin(), vecint.end(), bind(equal_to<int>(), _1, query))) {
cout << "found " << query << " in the container\n";
}
else {
cout << "your query: " << query << " is not inside the container\n";
}
// using lambda, here I am capturing the query variable
// into the lambda function
cout << "using any_of with lambda:\n";
if (any_of(vecint.begin(), vecint.end(),
[query](int val)->bool{ return val==query; })) {
cout << "found " << query << " in the container\n";
}
else {
cout << "your query: " << query << " is not inside the container\n";
}
}
int main(int argc, char* argv[]) {
testfind();
return 0;
}
Say this file is named 'testalgorithm.cpp' you need to compile it with
假设这个文件被命名为“testalgorithm.cpp”,你需要用它来编译它
g++ -std=c++11 -o testalgorithm testalgorithm.cpp
Hope this will help. Please update or add if I have made any mistake.
希望这会有所帮助。如果我犯了任何错误,请更新或添加。
回答by Antonin GAVREL
If you were originally looking for the answer to this question (int value in sorted (Ascending) int array), then you can use the following code that performs a binary search (fastest result):
如果您最初是在寻找这个问题的答案(int value in sorted (Ascending) int array),那么您可以使用以下代码来执行二分查找(最快的结果):
static inline bool exists(int ints[], int size, int k) // array, array's size, searched value
{
if (size <= 0) // check that array size is not null or negative
return false;
// sort(ints, ints + size); // uncomment this line if array wasn't previously sorted
return (std::binary_search(ints, ints + size, k));
}
edit: Also works for unsorted int array if uncommenting sort.
编辑:如果取消注释排序,也适用于未排序的 int 数组。
回答by Moises Rojo
Using NewtonC++
使用牛顿C++
bool exists_linear( INPUT_ITERATOR first, INPUT_ITERATOR last, const T& value )
bool exists_binary( INPUT_ITERATOR first, INPUT_ITERATOR last, const T& value )
the code will be something like this:
代码将是这样的:
if ( newton::exists_linear(arr.begin(), arr.end(), value) )
std::cout << "found" << std::endl;
else
std::cout << "not found" << std::endl;
both exists_linear and exists_binary use std implementations. binary use std::binary_search, and linear use std::find, but return directly a bool, not an iterator.
exists_linear 和 exists_binary 都使用 std 实现。二进制使用 std::binary_search,线性使用 std::find,但直接返回一个 bool,而不是迭代器。
回答by Jan
One wants this to be done tersely. Nothing makes code more unreadable then spending 10 lines to achieve something elementary. In C++ (and other languages) we have alland anywhich help us to achieve terseness in this case. I want to check whether a function parameter is valid, meaning equal to one of a number of values. Naively and wrongly, I would first write
人们希望这件事能够简洁地完成。没有什么比花费 10 行代码来实现一些基本的东西更难读的代码了。在C ++(和其他语言),我们有所有和任何我们能够在这种情况下,实现简洁哪些帮助。我想检查函数参数是否有效,即等于多个值之一。天真和错误地,我会先写
if (!any_of({ DNS_TYPE_A, DNS_TYPE_MX }, wtype) return false;
a second attempt could be
第二次尝试可能是
if (!any_of({ DNS_TYPE_A, DNS_TYPE_MX }, [&wtype](const int elem) { return elem == wtype; })) return false;
Less incorrect, but looses some terseness. However, this is still not correct because C++ insists in this case (and many others) that I specify both start and end iterators and cannot use the whole container as a default for both. So, in the end:
不那么不正确,但失去了一些简洁性。但是,这仍然不正确,因为在这种情况下(以及许多其他情况),C++ 坚持我指定开始和结束迭代器,并且不能将整个容器用作两者的默认值。所以,最后:
const vector validvalues{ DNS_TYPE_A, DNS_TYPE_MX };
if (!any_of(validvalues.cbegin(), validvalues.cend(), [&wtype](const int elem) { return elem == wtype; })) return false;
which sort of defeats the terseness, but I don't know a better alternative... Thank you for not pointing out that in the case of 2 values I could just have just if ( || ). The best approach here (if possible) is to use a case structure with a default where not only the values are checked, but also the appropriate actions are done. The default case can be used for signalling an invalid value.
哪种方式打破了简洁性,但我不知道更好的选择......感谢您没有指出在 2 个值的情况下我可以只拥有if ( || )。此处的最佳方法(如果可能)是使用具有默认值的案例结构,其中不仅检查值,而且执行适当的操作。默认情况可用于发出无效值的信号。
回答by canhazbits
C++ has NULL as well, often the same as 0 (pointer to address 0x00000000).
C++ 也有 NULL,通常与 0 相同(指向地址 0x00000000 的指针)。
Do you use NULL or 0 (zero) for pointers in C++?
So in C++ that null check would be:
所以在 C++ 中,空检查将是:
if (!foo)
cout << "not found";