调用 'begin(int**&)' 没有匹配函数
no matching function for call to ‘begin(int**&)’
我写了一个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::begin
和 std::end
。可以使用标准 C 数组,但不能使用指针。
相关文章:
- 在函数 'int main(int, char**) 中,没有声明 'MIN'
- 错误:无效使用非静态成员函数"int test::hotplug_callback(libusb_contex
- 重载函数 int vs double
- 错误 C2084:函数"int main(void)"已具有主体
- 无效使用非静态成员函数 int test::funcAB(int, int)
- 错误:函数"int open(...)"的隐式声明
- 如何在没有参数的情况下实现返回双向链表大小的函数?int size() const.
- 错误:参数太少,无法函数"int Solution(std::vector<int>, int)"
- arr++ 在函数"int f(int arr[])"中是什么意思?
- 带有声明帐户的C 构造函数(int = 0);
- 如何初始化一个在C++中期望向量和变量的构造函数<int>?
- C++,实现函数"int next(std::string param)"时出现奇怪的编译器错误
- 单链表交换函数(int,int)
- 插入 std::map<int, std::vector 的简短函数<int>>
- 函数int get()和istream&get(char&c)有什么区别
- 该函数 int f() 没有警告不返回任何值?
- 没有用于启动"ostream_iterator"的匹配构造函数<int>
- 函数"int __cdecl invoke_main(void)"中引用LNK2019未解析的外部符号_main错误 (?invoke_main@@YAHXZ)
- 函数"int (*function())[10];"是什么意思?
- 非成员函数 'int find(const T&)' 不能有 cv 限定符