c++ - STL::带有原始指针的迭代器

标签 c++ pointers stl

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

相关文章:

c++ - 使用二进制谓词在 find_first_of 函数上给出错误

c++ - 将 vector<T> 转换为 initializer_list<T>

c++ - 使用两个不同大小的一维数组制作二维数组

c++ - 为什么将可视化调试器附加到我的程序比直接从 visual studio 运行它更快?

c++ - 为什么总是在 mouseDoubleClickEvent 之前调用 mousePressEvent

c - 使用 Malloc 输入字符串后程序崩溃

c++ - STL最常用的部分是什么?

c++ - 重载 << 和 >> 运算符 : The program compiles but running it doesn't accept input

c++ - std::set of shared_ptr 的删除导致 SIGABRT

c++ - 返回值部分且确定性地变化