gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:29:10 25 4
gpt4 key购买 nike

我对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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com