c++ - 错误 “no matching function for call ' begin(int [len] )' ”在我的代码中是什么意思?

标签 c++ c++11

我对C++编码非常陌生,并且在C++入门第5版Ex 3.42中遇到了一个问题,该问题要求我使用 vector 元素初始化数组。
因此,我这样编写了代码,但无法理解为什么begin函数会抛出没有匹配函数的错误来调用。
我还尝试通过删除begin函数并使用arr初始化* pbeg来更正代码。
像这样 ,
int * pbeg = arr;
而且有效。
有人可以通过使用begin来解释为什么以及我做错了什么吗?

#include <iostream>
#include <vector>
#include <iterator>

using std::cin ;
using std::cout ;
using std::endl ;
using std::vector ;
using std::begin ;

int main()
{
    vector<int> ivec ;
    int i ;

    while(cin >> i)
        ivec.push_back(i) ;
    const auto len = ivec.size() ;
    int arr[len] , *pbeg = begin(arr) ;  // here it shows the error 
    for(auto c : ivec)
    {
        *pbeg = c ;
        ++pbeg ;
    }
    for(auto c : arr)
        cout << c << "," ;
    cout << endl ;
    return 0 ;
}

最佳答案

除了一些评论者已经指出的内容外,从本质上讲,您的问题可以归结为:必须在编译时知道数组的大小。如果未知,则可以使用std::vector或动态分配的C样式数组。
但是,由于这是一个硬件问题,因此以下内容可能会让您有所了解:

#include <iostream>
#include <vector>
#include <memory>

int main(void)
{
    std::vector<int> vec = {1, 2, 3, 4, 5};
    std::unique_ptr<int []> dyn_arr = std::make_unique<int []>(vec.size());
    auto arr_size = vec.size();

    for (auto i = 0; i < arr_size; i++)
    {
        dyn_arr[i] = vec[i];
    }

    for (auto i = 0; i < arr_size; i++)
    {
        std::cout << dyn_arr[i] << "\t";
    }

    std::cout << "\n";

    return 0;
}
注意:我已经使用unique_ptrint[],以便将内存管理部分卸载到该语言。
 valgrind ./dyn_array
==280== Memcheck, a memory error detector
==280== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==280== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==280== Command: ./dyn_array
==280==
==280== error calling PR_SET_PTRACER, vgdb might block
1       2       3       4       5
==280==
==280== HEAP SUMMARY:
==280==     in use at exit: 0 bytes in 0 blocks
==280==   total heap usage: 4 allocs, 4 frees, 76,840 bytes allocated
==280==
==280== All heap blocks were freed -- no leaks are possible
==280==
==280== For counts of detected and suppressed errors, rerun with: -v
==280== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

关于c++ - 错误 “no matching function for call ' begin(int [len] )' ”在我的代码中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62981847/

相关文章:

c++ - 哪些开源 COM 实现适用于嵌入式系统?

c++ - 基于范围的for循环和std::vector:元素是按顺序处理的吗?

c++ - 使用 C++11 的 STLPort

循环内的 C++ std::thread 同步

c++ - 两种数字比较方式哪一种更有效

c++ - 由于某些 python 错误,arm-none-eabi-gdb 无法启动

c++ - 定义一个像整数无穷大一样的对象

c++ - 使用模板时的编译错误

c++ - 位数 : preprocessor magic vs modern C++

c++ - 为什么在删除默认构造函数 A::A() 时编译 'A a{};'?