调用 'begin(int**&)' 没有匹配函数

no matching function for call to ‘begin(int**&)’

本文关键字:函数 int begin 调用      更新时间:2023-10-16

我写了一个c++程序作为fllow(3.43.cpp):

#include <iostream>
using std::cout;
using std::endl;
void version_1(int **arr) {
    for (const int (&p)[4] : arr) {
        for (int q : p) {
            cout << q << " ";
        }
        cout << endl;
    }
}
int main() {
    int arr[3][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
    version_1(arr);
    return 0;
}

然后我使用编译它:gcc my.cpp -std=c++11,有一个错误我无法处理。信息:

3.43.cpp:6:30: error: no matching function for call to ‘begin(int**&)’
     for (const int (&p)[4] : arr) {
                              ^
3.43.cpp:6:30: note: candidates are:
In file included from /usr/include/c++/4.8.2/bits/basic_string.h:42:0,
                 from /usr/include/c++/4.8.2/string:52,
                 from /usr/include/c++/4.8.2/bits/locale_classes.h:40,
                 from /usr/include/c++/4.8.2/bits/ios_base.h:41,
                 from /usr/include/c++/4.8.2/ios:42,
                 from /usr/include/c++/4.8.2/ostream:38,
                 from /usr/include/c++/4.8.2/iostream:39,
                 from 3.43.cpp:1:
/usr/include/c++/4.8.2/initializer_list:89:5: note: template<class _Tp> constexpr const _Tp* std::begin(std::initializer_list<_Tp>)
     begin(initializer_list<_Tp> __ils) noexcept

我在谷歌上搜索它,但没有找到类似的答案。

由于arr只是一个指针,因此无法推断它有多大。但是,由于您实际上是在传递一个真实数组,因此您可以只在其维度上模板化您的函数,以便通过引用获取实际数组,而不是让它衰减到指针:

template <size_t X, size_t Y>
void foo(const int (&arr)[X][Y])
{
    std::cout << "Dimensions are: " << X << "x" << Y << std::endl;
    for (const int (&row)[Y] : arr) {
        for (int val : row) {
            std::cout << val << ' ';
        }
        std::cout << std::endl;
    }
}
int main() {
    int arr[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
    foo(arr);
}

std::begin()std::end()不适用于指针。它们仅适用于数组。如果你想推断数组的大小,你需要把它作为函数的参考传递:

#include <cstddef>
template <std::size_t A, std::size_t B>
void version_1(int (&arr)[B][A]) {
    for (const int (&p)[A] : arr) {
        for (int q : p) {
            cout << q << " ";
        }
        cout << 'n';
    }
}
指针

与数组不同。为了能够使用基于范围的 for,您的容器必须支持 std::beginstd::end 。可以使用标准 C 数组,但不能使用指针。