C++ 检查元素是否存在于数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9079712/
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
C++ check if element exists in array
提问by RnD
I've found a lot of topics like this, but it was kinda too complicated for me.
我发现了很多这样的主题,但对我来说有点太复杂了。
How to check if element exists in an array?
如何检查元素是否存在于数组中?
first I declare an array and put values in it
首先我声明一个数组并将值放入其中
for(int l=0;l<=21;l++){
skirt[l]=l;
}
and then with another for
I'd like to check if any element which exist in other array is in array skirt[];
然后与另一个for
我想检查其他数组中存在的任何元素是否在数组中skirt[];
Is there a way to write it something like this?
有没有办法把它写成这样?
for(int k=0;k<=n;k++){
if(skaiciai[k]!=skirt[k]){
counter++;
}
}
采纳答案by hmjd
The loop:
循环:
for(int k=0;k<=n;k++){
if(skaiciai[k]!=skirt[k]){
counter++;
}
}
would only compare elements at the same index in the arrays. Nested for
loops are required with the outer for
loop iterating over the elements in one array and the inner for
loop iterating over elements in the other array:
只会比较数组中相同索引处的元素。for
需要嵌套循环,外for
循环迭代一个数组中的元素,内for
循环迭代另一个数组中的元素:
for (int k_skirt = 0; k_skirt <= n; k_skirt++)
{
for (int k_skaiciai = 0; k_skaiciai <= n; k_skaiciai++)
{
if(skaiciai[k_skaicia] == skirt[k_skirt]){
counter++;
}
}
}
回答by Mankarse
The best way to do this would be to use standard algorithm, rather than a handwritten loop:
最好的方法是使用标准算法,而不是手写循环:
if (std::find_first_of(
skirt, skirt + skirt_size,
skaiciai, skaiciai + skaiciai_size)
!= skirt + skirt_size)
{
//skirt contained an element from skaiciai
}
回答by Klaim
You could simply use the std::count algorithm.
您可以简单地使用 std::count 算法。
auto counter = std::count( skirt, skirt+skirt_size );