简体   繁体   中英

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] . In fact, attempting to print it out using printf gives me a warning:

warning: format '%p' expects argument of type 'void*' , but argument 3 has type '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.

for a vector object v1:

&V[0] is the the address of first element of the object v1.

when we create an iterator eg vector<>::iterator iter the iter itself is an other object as explain in this document .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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