Now I want to get item "1" 's address, Can I do:Code:vector<int> vec;
vec.push_back(1);
vector<int>::iterator it = vec.begin();
?Code:int* pint = &*it
Printable View
Now I want to get item "1" 's address, Can I do:Code:vector<int> vec;
vec.push_back(1);
vector<int>::iterator it = vec.begin();
?Code:int* pint = &*it
Yes.
The &*it looks awkward. Does vector iterator provide an off-the-shelf method?
That's because you aren't supposed to take the address of something stored in an iterator.
Iterators are C++'s version of pointers. They're much more flexible.
So unless you have to - don't do it. There's a reason why there's no easy way.
With a vector, you can do &vec[0], because it's guaranteed to be contiguous. Other containers are not.
>> Does vector iterator provide an off-the-shelf method?
No. It is rare that you would need a pointer to an item in a vector, so there's no reason for that to be part of the vector's direct interface.
You have to get a reference to the object then take its address. There are other ways to get the reference to the object besides using an iterator. Here are a couple other examples:Note that when you're not using a temporary or iterator (as in #5 and #6) you want to use a reference variable, otherwise you'll be making a copy and taking the address of that.Code:vector<int> vec;
vec.push_back(1);
int* pint1 = &(*vec.begin());
int* pint2 = &(vec.at(0));
int* pint3 = &(vec[0]);
vector<int>::iterator it1 = vec.begin();
int* pint4 = &(*it1);
int& rint1 = vec.at(0);
int* pint5 = &(rint1);
int& rint2 = vec[0];
int* pint6 = &(rint1);
>> With a vector, you can do &vec[0], because it's guaranteed to be contiguous. Other containers are not.
This is true, but is not relevant to the question. You can do &vec[0] with any container that supports operator[] to get a pointer to the first element, which is what was being discussed.
Just a caution, because most of the time you may want a pointer to the first element is to pass it as a pointer to a function that expects that pointer to point to an array.
Also, don't expect the pointer you create to stay valid forever, because STL containers can reallocate their internal memory when they need more space, and then you have a pointer that points to deallocated memory.
And finally, you can't do this stuff with vector<bool>, because it's completely broken.