我将什么传递给函数,以便能够自动迭代数组?

时间:2014-03-09 02:10:45

标签: c++ c++11

我想自动移动到count_x()函数中char数组中的下一项。我的数组初始化需要看起来是什么样的,或者我应该如何传递我的参数以便能够使用以下函数?

int count_x(char* p, char x)
     // count the number of occurrences of x in p[]
     // p is assumed to point to a zero-terminated array of char (or to nothing)
{
     int count = 0;
     while (p) {
          if (*p==x)
                ++count;
          ++p;
     }
     return count;
}

看到第三行?评论?那是在唠叨我。零终止意味着数组中的最后一个元素是nullptr还是什么?

2 个答案:

答案 0 :(得分:3)

编辑中的示例和原始代码实际上是两个完全不同的东西。

在C中,char[]用于表示“字符串”;一堆字节将被映射到终端或窗口系统设置的某些字符供人类使用。

字符串是“空终止”;通过在数组中放置0,在数组上运行的函数知道指示字符串的结尾。 (这稍微掩盖了一些事情,因为0被明确定义为终止C中的字符串,而UTF-8和US-ASCII例如明确地将0定义为“空字符”。 / p>

你的第一个例子是处理int ...这里没有终止值,除非你这样定义一个。这完全取决于方法的预期输入。一个简单的例子是将-1定义为“毒丸”并检查:

让我们说你重新定义了你的数组:

int v[] = {0,1,2,3,4,5,6,7,8,8,8,9,-1};

现在你的while语句看起来像:

while(*p_int_array != -1) {

根据评论进行修改:

由于您编辑的Q完全是关于字符串的...字符串文字自动为空终止:

char *foo = "hi!";

真的

char foo[] = {'h','i','!', 0}; // or, '\0'  

那就是说,你现在展示的例子是错误的,并且会出现错误。它需要查看p指向的内容,而不是指针(内存地址)本身。

while (*p) {

答案 1 :(得分:1)

最好的方法是使用标准库中的向量,但是你可以通过传递数组的长度和更改循环来实现这一点,或者这可能是最糟糕的解决方案,但保留了当前的方法:

int count_if(int* p_int_array, int * p_last_object, int desired_value)
{
    int count = 0;

    // I want this loop and the ++p_int_array below
    // to work together to iterate through an array.
    while(p_int_array != p_last_object) {
        int current_int = *p_int_array;
        if(current_int == desired_value)
            ++count;
        ++p_int_array;
    }

    return count;
}
void print()
{
    int v[] = {0,1,2,3,4,5,6,7,8,8,8,9};

    int desired_value = 8;

    // What should I pass into count_if, in order to get the
    // loop "while(p_int_array)" to work?
    // Also, do the names adhere to naming conventions in C++
    int count = count_if(&v[0], &v[11], desired_value);

    cout << "There are " << count << " " << desired_value << " in v\n";
}