If语句未能激活

If statement failing to activate

本文关键字:激活 语句 If      更新时间:2023-10-16

我想创建一个函数,应该做以下事情:

-取两个字符数组,一个比另一个小,并确定较小的字符数组是否是较大数组的子集。举个例子:阵列A: {"s","c","h","o","o","l"};阵列B: {"c","h"}。我必须使用指针自增/自减操作。这是我生成的代码:

int locator(char *Bigptr, char *Smallptr) {
int count = 0;
    for (; *Bigptr != ''; Bigptr++) {
        if (*Smallptr == *Bigptr) {
            for (; (*Smallptr == *Bigptr) != ''; Smallptr++, Bigptr++) {}
            if (*Smallptr == '') {
                return count;
            }
            else {
                cout << "small is not the subset of big" << endl;
                return 0;
            }
        }
        count++;
    }
return 0; 

我认为代码应该是这样运行的:

两个指向字符数组的指针作为函数'locator'的形参。变量count是我为了告诉我A中出现的第一个字符的下标是什么而放置的(例如:"school"answers"ch"是元素1,所以A[1])。第一个for循环确保较大数组的第一个值是一个实际字符。if语句在发现一个共同字符时返回true。然后,第二个for循环检查是否所有较小的数组都存在于较大的数组中。当我的程序编译时,所有这些都按预期工作。嵌套的if语句出现问题。如果小数组是大数组的子集,我期望它是成立的。为什么不是这样呢?以"school"answers"ch"为例。*Smallptr最初指向数组B的第一个元素(即:"ch"),所以是"c"。然后将其与"学校"中的"c"进行比较。然后对两个指针进行自增,使它们都指向各自数组中的"h"。同样,它们再次递增,使*Bigptr指向"0",*Smallptr指向""。事实并非如此吗?为什么函数总是输出else语句?

你对第二个for循环的理解是错误的。

if (*Smallptr == *Bigptr) {
    for (; (*Smallptr == *Bigptr) != ''; Smallptr++, Bigptr++) {}

由于您已经确定(在if条件下该语句)*Smallptr == *Bigptr,该比较给出了非零(true)结果。

测试(*Smallptr == *Bigptr) != ''将非零结果与值为零的char进行比较。非零值永远不会比较为零(至少,不包括bool在内的标准整型),因此循环不起作用。

符合描述的循环是

for (; (*Smallptr == *Bigptr) && *SmallPtr != ''; Smallptr++, Bigptr++) {}

检查两个字符是否相等,且都非零。

考虑到这是c++,您可能希望利用标准库中已经存在的功能。我要按这个顺序做:

bool is_subset(std::string big, std::string small) { 
    std::sort(big.begin(), big.end());
    std::sort(small.begin(), small.end());
    std::string result;
    std::set_difference(small.begin(), small.end(),
                        big.begin(), big.end(),
                        std::back_inserter(result));
    return result.empty();
}

这不能满足使用指针的要求,但在我看来,这是一种更好的方法。

for (; (*Smallptr == *Bigptr) != ''; Smallptr++, Bigptr++) {}

是不正确的

你需要的是:

for (; (*Smallptr == *Bigptr) && *SmallPtr != ''; Smallptr++, Bigptr++)
{
   ++count;
}

你有几个地方错了。看看这个返工:

int locator(char *Bigptr, char *Smallptr) {
    int count = 0;
    for (; *Bigptr != ''; Bigptr++) {
        if (*Smallptr == *Bigptr) {
            for (; *Smallptr == *Bigptr && *Bigptr!=''; Smallptr++, Bigptr++) {
                count++;
            }
            if (*Smallptr == '') {
                return count;
            }
            break; //this is necesary in order not to stay in the main for loop
        }
    }
    std::cout << "small is not the subset of big" << std::endl;
    return count;
}

EDIT:在main函数中测试代码,它工作得很好:

int main(int argc, const char * argv[]) {
    std::cout << locator("hello","ohl"); //this prints "small is not the subset of big"
    std::cout << locator("hello","ell"); //this prints "3" (the count of matching characters)
    return 0;
}