[英]no matching function for call to ‘begin(int**&)’
I wrote a c++ program as fllow(3.43.cpp): 我写了一个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;
}
Then I compile it by using: gcc my.cpp -std=c++11
, there is an error I can not deal with. 然后我使用: gcc my.cpp -std=c++11
编译它,有一个我无法处理的错误。 Info: 信息:
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
I search it in google, but not find similar answer. 我在谷歌搜索它,但没有找到类似的答案。
Since arr
is just a pointer, there's no way to deduce how big it is. 由于arr
只是一个指针,因此无法推断它有多大。 But, since you are actually passing in a real array, you can just template your function on its dimensions so you take the actual array by reference rather than having it decay to a pointer: 但是,既然你实际上是在传入一个真正的数组,你可以在你的维度上模拟你的函数,这样你就可以通过引用获取实际的数组而不是让它衰减到指针:
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()
and std::end()
won't work for pointers. std::begin()
和std::end()
不适用于指针。 They only work for arrays. 它们只适用于数组。 If you want to deduce the size of your array you'll need to pass it as a reference your function: 如果你想推断你的数组的大小,你需要将它作为参考传递给你的函数:
#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';
}
}
Pointers are not the same as arrays. 指针与数组不同。 To be able to use range based for, your container must support std::begin
and std::end
. 为了能够使用基于范围的,您的容器必须支持std::begin
和std::end
。 Standard C arrays can be used, but not pointers. 可以使用标准C数组,但不能使用指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.