我是 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/