将值与一个语句中的所有数组元素进行比较

cpx*_*cpx 5 c++

例如:

if (value == array[size]) //if the value (unique) is present in an array then do something
Run Code Online (Sandbox Code Playgroud)

这可以在一个语句中完成,而不必调用函数或基本的for循环语句?

Ste*_*hen 5

std::find 可以在一个声明中做到这一点,但它并不像其他语言那样微不足道:(

int array[10];
if (array + 10 != find(array, array + 10, 7)) {
  cout << "Array contains 7!";
}
Run Code Online (Sandbox Code Playgroud)

或者std::count:

if (int n = count(array, array + 10, 7)) {
  cout << "Array contains " << n << " 7s!";
}
Run Code Online (Sandbox Code Playgroud)

  • @Gollum,OP在一份声明中要求它,我在一份声明中给了他.;)我个人不会将此方法用于数组.使用其他容器或使用`contains`辅助函数更简单. (3认同)
  • @Gollum,这个复杂的C++怎么样?你建议把这个find()调用传播到更多行吗? (3认同)