简体   繁体   English

错误:没有用于调用'begin(int *&)'c ++的匹配函数

[英]error: no matching function for call to 'begin(int*&)' c++

#include <iostream>
#include <iterator>
using namespace std;
void print(int ia[])
{
    int *p = begin(ia);
    while(p != end(ia))
        cout<<*p++<<'\t';
}

int main()
{
    int ia[] = {1,2,3,4},i;
    print(ia);

    return 0;
}

P pointer to the first element in ia. P指向ia中的第一个元素。 why it said"error: no matching function for call to 'begin(int*&)' c++" thanks!:) 为什么它说“错误:没有匹配函数来调用'begin(int *&)'c ++”谢谢!:)

Because inside print() , the variable ia is a pointer, not an array. 因为在print()内部,变量ia是指针,而不是数组。 It doesn't make sense to call begin() on a pointer. 在指针上调用begin()没有意义。

You are using the begin and end free functions on a pointer, that's not allowed. 您正在指针上使用beginend自由函数,这是不允许的。

You can do something similar with C++11's intializer_list 您可以使用C ++ 11的intializer_list执行类似的操作

//g++ -std=c++0x test.cpp -o test
#include <iostream>
#include <iterator>
using namespace std;
void print(initializer_list<int> ia)
{
    auto p = begin(ia);
    while(p != end(ia))
        cout<<*p++<<'\t';
}

int main()
{
    print({1,2,3,4});   
    return 0;
}

As others pointed out, your array is decaying to a pointer. 正如其他人指出的那样,你的数组会衰减为指针。 Decaying is historical artifact from C. To do what you want, pass array as reference and deduce array size: 衰减是来自C的历史人工制品。要做你想要的,传递数组作为参考并推导出数组大小:

template<size_t X>
void print(int (&ia)[X])
{
    int *p = begin(ia);
    while(p != end(ia))
        cout<<*p++<<'\t';
}

print(ia);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM