c - 验证表中元素是否存在

标签 c algorithm

我是 C 算法新手,前来寻求帮助。

我希望检查表中是否存在某个元素,有人可以给我一些好的算法吗?我所做的是一个循环和一个标志,然后退出循环并验证标志。但它看起来很愚蠢,所以我想会有更有效的算法。我的代码如下:

int j=0;
u8_t next_header[]={0x11, 0x22}; 
for(i = 0; i < sizeof(next_header); ++i)
{       
    if (buf[6] != next_header[i])
        continue;
    else
        ++j;            
}
if(j == 0)
{
// execution    
}
else
{
// execution
}

最佳答案

将其打包在一个函数中,这样一旦找到该元素就可以使用 return 跳出循环:

int search_for_elements(int element)
{
    int i;
    u8_t next_header[]={0x11, 0x22}; 
    for(i = 0; i < sizeof(next_header); ++i)
    {       
        if (element == next_header[i])
            return 1; // found the element;
    }
    return 0; // :( no element found
}

关于c - 验证表中元素是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23813716/

相关文章:

c - 在 C 中使用 OpenSSL 加密字符串

c - 查找以太网 header 的下一跳 MAC 地址

python - 用餐哲学家的非阻塞解决方案

algorithm - 找到随机数组中的最大增量

python - 图像分析 : separating intersecting spaghettis

c - 如何生成8字节的十六进制值?

c - 相同的代码+二进制在不同的机器上给出不同的结果

c - 如何使用 C 中的 GStreamer 连接到 UDP 视频广播

algorithm - 关于连通性的图论

javascript - 使用正则表达式突出显示一组字符串