我想对 C++ 数组使用迭代器,但也想对原始指针使用迭代器。 我可以使用静态 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);
如何使用原始指针(可能是堆分配的 vector )来做到这一点? 编译器当然不知道数据的大小,所以这段代码
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
是不可能的(因为如你所说,大小未知) ,所以它有点毫无意义。
但是,您不需要其中任何一个来使用 std::find
:
int* p = std::find(pStart, pStart + SIZE, 5);
关于c++ - STL::带有原始指针的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41962903/