c++如何检查数组中的元素是否相等
C++ how to check if elements in an array are equal?
我正试图编写一个程序,检查是否在一个数组中的所有值是相等的使用for循环,但我无法找出一种方法,如果语句检查数组中的每个值是否相等,而不是不断重复"if a[i] == a[1] && a[i] == a[0]"
等。我不想这样做,因为我想让它适用于任何大小的数组。任何帮助都非常感激!
for (unsigned i = 0; i < val; i++){
if (a[i] == a[0])
return true;
else
return false;
}
for (unsigned i = 0; i < val; i++) {
if (a[i] != a[0]) {
return false;
}
}
return true;
应该可以了。
在这种情况下,代码将在不匹配的值上立即失败。然而,对于匹配的值,它只是继续检查(我们知道我们需要测试数组的每个元素,无论如何)。一旦完成,它就知道一切正常(因为我们没有提前返回),并返回true。
#include <algorithm>
#include <vector>
#include <iostream>
int main(int argc, char** argv)
{
std::vector<int> eq{ 1, 1, 1, 1 };
std::vector<int> nq{ 1, 2, 1, 1 };
bool eq_res = std::all_of(std::begin(eq), std::end(eq),
[&eq](int c) -> bool
{
return eq[0] == c;
});
bool nq_res = std::all_of(std::begin(nq), std::end(nq),
[&nq](int c) -> bool
{
return nq[0] == c;
});
std::cout << "eq: " << eq_res << std::endl;
std::cout << "nq: " << nq_res << std::endl;
}
编制c++——std=c++11 main.cpp
只是为了好玩,使用lambda表达式
#include <algorithm>
using namespace std;
template<size_t N>
bool func(int (&arr)[N])
{
int* pOddValue = std::find_if(begin(arr), end(arr),
[&] (int val){ return val != arr[0];});
return pOddValue != end(arr);
}
使用分治法,当n = 2^k时,我们可以像这样将比较次数减少到n-1:
bool divide(int arr[],int size)
{
if( size == 2 ) return arr[0] == arr[1];
if( divide(arr,size/2) && divide(arr+size/2,size/2) )
return arr[0] == arr[size/2];
return false;
}
另一种类似的方法:
for (unsigned i = 1; i < val; i++) {
if (a[i] != a[i-1]) {
return false;
}
}
return true;
似乎不需要处理val = 0。你可以在一行内完成。
#include <functional>
#include <algorithm>
using namespace std;
return all_of(
a+1, a+val,
bind(equal_to<remove_pointer<decltype(a)>::type>(), a[0], placeholders::_1));
相关文章:
- C++默认情况下,指针类型数组的元素是否保证初始化为 nullptr?
- 检查 2D 网格的某个元素是否与另一个元素共享对角线、水平线或垂直线
- 如何知道地图中的最后一个元素是否被删除?
- 检查 TinyXML 中的元素是否存在
- 使用 at() 访问 std::map 元素是否比运算符 [] 慢?
- 在迭代期间添加到 std::unordered_set(或 unordered_map)中的元素是否会在迭代期间访问?
- 使用 Rcpp 加速替换迭代算法中的列表和向量元素是否合法?
- 通过引用访问矢量元素是否会降低C++的空间复杂性?
- 检查HTML 5视频元素是否正在获取帧
- 在c++中,如何检查一个数组的元素是否也是另一个数组中的元素
- 是否有更有效的方法来检查元素是否在给定的区间内
- 如何检查数组的 3 个元素是否具有相同的值
- 整数指针数组的元素是否可以指向整数数组?
- 在 new 关键字中,由默认构造函数初始化的类中的元素是否也使用 new 关键字在C++?
- 写入多维矢量子级中的元素是否安全?
- 使用容器中元素的别名删除带有 std::list::remove 的元素是否正确?
- 如何确定向量的元素是否交替为符号?
- 如何查看矢量中的所有元素是否相同?
- 从标准容器中移动元素是否合法?
- 如何检查 std::vector<std::string> 的元素是否以某个子字符串开头?