gpt4 book ai didi

c - 如何在不使用计数器的情况下检查数组的元素是否都相同?

转载 作者:太空宇宙 更新时间:2023-11-04 06:01:25 24 4
gpt4 key购买 nike

假设我有一个数组

 bool string[N]={false};

经过一些操作后,数组字符串的所有元素都变为真。我想在 if 语句中检查此条件,如下所示:-

伪代码--

if(all the elements of string are same or equal)
then do this

我如何实现这一目标?我不应该使用像这样的计数器

for(int i=0;i<N;i++)   //or something else like this 

最佳答案

PP 只需要稍微修改一下他的代码,他暗示的答案是:-

if (memcmp (&string [0], &string [1], sizeof string [0] * (N - 1)) == 0)
{
/* all elements the same */
}

N-1 停止溢出缓冲区的末尾。

memcmp 将字符串 [0] 与字符串 [1] 进行比较,然后将字符串 [1] 与字符串 [2] 进行比较,然后将字符串 [2] 与字符串 [3] 进行比较,依此类推,直到字符串 [n-2] 和字符串[n-1].

关于c - 如何在不使用计数器的情况下检查数组的元素是否都相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19033521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com