简体   繁体   English

C ++ vector.begin()和vector [0]

[英]C++ vector.begin() and vector[0]

why this two line prints different addresses? 为什么这两行打印不同的地址?

vector<int> v1{ 12,2,34 };
printf_s("%d -  0x%p\n", v1[0], &v1[0]);
printf_s("%d -  0x%p\n",*v1.begin(), v1.begin());

Values in this addresses are same but address itself is different. 该地址中的值相同,但地址本身不同。 Does it mean that there is two copy of the same array? 这是否意味着同一数组有两个副本?

EDIT : In debug mode it prints different addresses, in release mode there are same addresses :) 编辑 :在调试模式下它打印不同的地址,在发布模式下有相同的地址:)

v1.begin() returns an std::vector<int>::iterator , which is not necessarily an address to v1[0] . v1.begin()返回一个std::vector<int>::iterator ,它不一定是v1[0]的地址。 In fact, attempting to print it out using printf gives me a warning: 实际上,尝试使用printf将其打印出来会给我一个警告:

warning: format '%p' expects argument of type 'void*' , but argument 3 has type 'std::vector::iterator` 警告:格式'%p'期望类型为'void *'的参数,但是参数3的类型为'std :: vector :: iterator`

Unless you're sure that in your particular Standard Library implementation and with your current compilation options std::vector<int>::iterator is an alias for int* , the comparison is meaningless. 除非您确定在特定的标准库实现中并且使用当前的编译选项std::vector<int>::iteratorint*的别名,否则比较是没有意义的。

for a vector object v1: 对于矢量对象v1:

&V[0] is the the address of first element of the object v1. &V[0]是对象v1的第一个元素的地址。

when we create an iterator eg vector<>::iterator iter the iter itself is an other object as explain in this document . 当我们创建一个迭代例如vector<>::iterator iteriter本身是一个其他对象,因为这在解释文件

Iterator: a pointer-like object that can be incremented with ++, dereferenced with *, and compared against another iterator with !=. 迭代器:类似指针的对象,可以用++递增,用*取消引用,然后与!=的另一个迭代器进行比较。

I hope this reference manual answer your question in detail. 希望本参考手册能详细回答您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM