c++ - 使用C++11的begin()和end()函数通过参数确定数组维数

标签 c++ arrays c++11

所以我目前正在学习 C++(之前有 Java 和 JavaScript 方面的经验),据我所知,你不能像在 Java 中那样在 C++ 中将数组作为参数传递。但是您可以将指针传递给数组中的第一个元素。所以我可以像这样遍历数组:

bool occurs(int* arrInt, int length, int sought, int& occurrences)
{
    for (int i = 0; i <= length; ++i)
    {
        if (arrInt[i] == sought)
            occurrences++;
    }

    // if occurences > 0 return true, else false
    return occurrences;
}

整个函数基本上应该返回一个 bool 值,告诉我是否在数组 (arrInt) 中找到给定的 int (sought)。此外,我还通过引用提供了一个小计数器(occurrences)。 但是令我烦恼的是 length 参数。 C++11 提供了那些花哨的 std::begin/cbegin() 和 std::end/cend() 函数来获取数组的第一个和最后一个元素:

int arr[] = {1,2,3,4} // arr is basically a pointer to an int, just as the
                      // function parameter of ocurs(int*,int,int,int&)
auto end = std::end(arr); // end points to one past last element

但为什么我不能使用我的 arrInt 参数作为该函数的参数?然后我可以摆脱长度参数:

bool occurs(int* arrInt, int sought, int& occurences)
{
    for (auto it = std::begin(arrInt); it != std::end(arrInt); ++it)
    {
        if (*it == sought)
            occurences++;
    }

    // if occurences > 0 return true, else false
    return occurences;
}

我是否遗漏了一个主要概念?提前致谢

最佳答案

在你的第一个例子中:

int arr[] = {1,2,3,4} // arr is basically a pointer to an int, just as the
                      // function parameter of ocurs(int*,int,int,int&)
auto end = std::end(arr); // end points to one past last element

arr 不是“基本上是一个指向 int 的指针”。 arr类型为 int[4] .请注意,长度是类型的一部分。结果,编译器可以很容易地确定“过去的最后一个元素”在哪里。只需添加长度即可。

可能会引起混淆的是 arr可转换到(你有时会听到衰减到)int* .但它不仅仅是一个指针。


在你的第二个例子中:

bool occurs(int* arrInt, int sought, int& occurences)
{
    for (auto it = std::begin(arrInt); it != std::end(arrInt); ++it) {
        ...
    }
    ...
}

arrInt 只是一个指针。因此,你怎么知道在哪里end()是?这里没有信息。这就是您需要额外长度参数的原因。

您也可以传递完整的数组,但必须通过引用来传递(您不能通过值传递数组,感谢 C!)。为此,您必须将其设为函数模板:

template <size_t N>
bool occurs (int (&arrInt)[N], int sought, int& occurrences) {
    ...
}

在这里,arrInt是一个数组 - 它的长度以类型( N )编码。所以你可以写std::end(arrInt) .


occurs()基本上是重写 std::count ,因此您可以改用它:

int arr[] = {1, 2, 3, 3, 8};
int occurrences = std::count(std::begin(arr), std::end(arr), 3); // yields 2

或者,更简单,使用 std::vector<int> .

关于c++ - 使用C++11的begin()和end()函数通过参数确定数组维数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35819048/

相关文章:

java - 如何读取数组中的字符输入?

javascript - 使用 JS 寻找我的过滤器函数的较短版本

c++ - 如何在派生类数据中使用基类进行比较

c++ - 如何使用 xlib 识别顶级 X11 窗口?

c++ - C++ 中的复制控制

c# - 在具有非不同元素的数组中查找局部最小值

c++ - 使用 typename::的模板结构特化

c++ - 如何为 Windows 编写一个无法杀死的进程?

c++ - 在 A 或 B 的任何容器上重载模板成员函数

c++ - 多态智能指针的使用