c++ - 为什么我不能将 std::begin/std::end 与 int(*p)[3] 一起使用,而我可以与 int(&p)[3] 一起使用?

标签 c++

这个有效:

void foo(int (&a)[3]) {
    auto ibegin = begin(a);
    auto ebegin = end(a);
}

虽然这不是:

void foo(int (*a)[3]) {
    auto ibegin = begin(a);
    auto ebegin = end(a);
}

我认为int (&a)[3]int (*a)[3]是同一个意思!

最佳答案

您的代码类似于:

void foo(vector<int>& a) {
    auto ibegin = begin(a);
    auto ebegin = end(a);
}

void foo(vector<int>* a) {
    auto ibegin = begin(a);
    auto ebegin = end(a);
}

第一个有效,第二个无效,原因与它在 int (&a)[3] 上有效而在 int (*a)[ 上无效相同3]。当您使用指向集合的指针而不是引用时,您需要在将它们传递给标准库的 begin/end 时取消引用它们。

void foo(vector<int>* a) {
    auto ibegin = begin(*a);
    auto ebegin = end(*a);
}

void foo(int (*a)[3]) {
    auto ibegin = begin(*a);
    auto ebegin = end(*a);
}

关于c++ - 为什么我不能将 std::begin/std::end 与 int(*p)[3] 一起使用,而我可以与 int(&p)[3] 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50341627/

相关文章:

c++ - 我的函数的返回结果是打印到控制台,只有在我称之为 C++ 时它才会工作

c++ - Boost::MSM:转换优先级

c++ - 具有自定义索引的数组

c++ - 如何对成员函数使用隐式类型转换?

c++ - Lua C++ lib sethook : Gives error with hook function arg

c++ - 在另一个线程中创建 QNetworkAccessManager

c++ - 如何克服 MSVC 成员方法指针模板参数推导失败的 bug?

c++ - 在 Android Studio 中为 C/C++ 添加包含路径

c++ - MFC VC++ 自定义复选框图像

c++ - 添加 vector 时出现段错误。 (C++)