c++ - 通过指针访问 std::vector 元素与 end()

标签 c++ pointers c++11

我需要能够通过指针访问(只读,不涉及调整大小或类似的东西)std::vector 的元素。例如,

std::vector<int> foo(10);
int *ptr_begin = &foo[0];

到目前为止一切顺利,保证在当前标准 (23.3.6.1) 中工作:

The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().

因此我们可以使用指针访问 vector 的所有元素,因为它们存储在连续的内存块中。但是最后一个元素呢?我的意思是,执行此操作是合法的?

int *ptr_end = ptr_begin + foo.size()

(请注意,我并不是要访问最后一个值,而只是定义一个指向它的指针——如果您愿意,它相当于 foo.end())。该标准只提到通过指针算法访问元素,但很明显这里我们没有访问任何元素。

(作为旁注,过去最后某物的存在的定义似乎与数组的基本概念紧密相关(例如参见 5.7/5),但在整个标准中它似乎是连续存储和数组可以互换使用。我读错了吗?)

最佳答案

是的,只要您只在比较中使用 ptr_end* 并且不尝试遵从它,就可以了。引用 C++11 标准草案第 5.7 节关于指针的加法运算(重点是我的):

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

§ 5.9 中为关系运算符列出了类似规定:

If two pointers point to elements of the same array or one beyond the end of the array, the pointer to the object with the higher subscript compares higher.

关于 vector 的缓冲区是否算作上述目的的数组,§ 8.3.4 指出:

An object of array type contains a contiguously allocated non-empty set of N subobjects of type T.

这与 § 23.3.6.1 中关于vector 的内容一致:

The elements of a vector are stored contiguously


因为指针是迭代器,所以这种事情对于使用标准库算法和任意内存块作为输入来说是一个方便的技巧。例如,假设您想使用 lower_bound 算法,但您的数据存储在 MFC CArray 中:

CArray<int> someInts;
// populate and check for empty
int* begin = someInts.GetData();
int* end = begin + someInts.GetSize(); // for bounds-checking only; don't dereference
int* answer = std::lower_bound(begin, end, 100);

*还有一些其他操作也是合法的;例如由于您知道 vector 不为空,因此可以减去一个以获得指向最后一个元素的指针。重要的是不要取消引用。

关于c++ - 通过指针访问 std::vector 元素与 end(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23635310/

相关文章:

c - 如何在 C 语言中对全局变量进行类型转换

c - 错误不兼容的指针类型?

c - 传递结构指针的问题和 "conflicting types"错误

c++ - 带字符串文字的自动

c++ - 为什么要在私有(private)继承下覆盖?

c++ - 如何到达 2d std::vector (`std::vector< std::vector<T>>` ) 的第 N 个元素?

c++ - 双重简单的 for 循环与一个复杂的循环

c++ - 如何使用 getopt_long 解析多个参数?

c++ - 传递二维数组,适用于 C 但不适用于 C++

C++11 std::thread std::move 提示尝试使用已删除的函数