问题描述
我想对 C++ 数组使用迭代器,但也要使用原始指针.我可以使用静态向量:
I want to use iterators with C++ arrays, but with raw pointers too.I can do with a static vector:
#define SIZE 10
int vect[SIZE] = {0};
vect[3] = 5;
int* p = std::find(std::begin(vect), std::end(vect), 5);
bool success = p != std::end(vect);
如何使用原始指针(可能是堆分配的向量)来做到这一点?当然编译器不知道数据的大小,所以这段代码
How can be possible to do it with a raw pointer (maybe a heap allocated vector)?Of course the compiler does not know the size of the data, so this code
int* pStart = vect;
std::find(std::begin(pStart), std::end(pStart), 5);
给予
error C2784: '_Ty *std::begin(_Ty (&)[_Size])' :
could not deduce template argument for '_Ty (&)[_Size]' from 'int *'
是否可以让 begin()
和 end()
意识到它?
Is it possible to make begin()
and end()
aware of it?
推荐答案
不,不能在指针上使用 std::begin
和 std::end
.不像数组的大小是类型的一部分,因此可以推导出指针不保存它指向的东西的大小.在您使用指针的情况下,您必须使用
No it is not possible to use std::begin
and std::end
on a pointer. Unlike an array whose size is part of the type and therefor deducible a pointer does not hold the size of the thing it points to. In your case with a pointer you would have to use
std::find(pStart, pStart + SIZE, 5);
避免这种情况的方法是使用 std::vector
当您在编译时不知道 szie 将是什么时.它将为您管理内存并提供begin
和end
成员函数.
The way to avoid this though is to use std::vector
when you are not going to know what the szie will be at compile time. It will manage the memory for you and provides begin
and end
member functions.
这篇关于stl::带原始指针的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!