【问题标题】:What is the meaning of the error "no matching function for call 'begin(int [len])' " in my code?我的代码中的错误“no matching function for call 'begin(int [len])'”是什么意思?
【发布时间】:2020-11-08 21:43:48
【问题描述】:

我是 C++ 编码的新手,在 C++ 入门第 5 版 Ex 3.42 中遇到了一个问题,要求我用向量的元素初始化一个数组。

所以,我写了这样的代码,但我不明白为什么 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 ;
}

【问题讨论】:

  • 为什么要在这里使用VLA (int arr[len]) 而不是vector?还有为什么要使用begin
  • 您正在尝试使用可变长度数组 (VLA),即 int arr[len]。这不是标准 C++ 的特性;一些编译器接受它作为非标准扩展。 std::begin 适用于标准数组,但不适用于 VLA。
  • 你不能只做你描述的,因为你描述的不是 C++ 语言的一部分。您所描述的某些变体适用于您的特定编译器,因为您的编译器支持该语言的某些非标准扩展,因此接受某些实际上不是有效的 C++ 程序的程序。
  • 如果你在一本书中找到了这段代码,那么那本书没有教标准 C++。
  • 在标准 C++ 中,数组维度必须是编译时常量。而ivec.size() 只能在运行时知道。在标准 C++ 中,std::vector 应该用于需要具有动态(仅在运行时知道)大小的数组。

标签: c++ c++11


【解决方案1】:

除了一些评论员已经指出的内容之外,基本上您的问题归结为:必须在编译时知道数组的大小。如果不知道,那么您将使用 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_ptr 用于int[],以便将内存管理部分卸载到语言中。

 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-24
    • 2022-01-13
    • 2019-10-16
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多