Convert iterator to pointer?
here it is, obtaining a reference to the coresponding pointer of an iterator use :
example:
string my_str= "hello world";
string::iterator it(my_str.begin());
char* pointer_inside_buffer=&(*it); //<--
[notice operator * returns a reference so doing & on a reference will give you the address].
That seems not possible in my situation, since the function I mentioned is the find function of
unordered_set<std::vector*>
.
Are you using custom hash/predicate function objects? If not, then you must pass unordered_set<std::vector<int>*>::find()
the pointer to the exact vector that you want to find. A pointer to another vector with the same contents will not work. This is not very useful for lookups, to say the least.
Using unordered_set<std::vector<int> >
would be better, because then you could perform lookups by value. I think that would also require a custom hash function object because hash
does not to my knowledge have a specialization for vector<int>
.
Either way, a pointer into the middle of a vector is not itself a vector, as others have explained. You cannot convert an iterator into a pointer to vector without copying its contents.
If you can, a better choice may be to change the function to take either an iterator to an element or a brand new vector (if it does not modify).
While you can do this sort of things with arrays since you know how they are stored, it's probably a bad idea to do the same with vectors. &foo[1]
does not have the type vector<int>*
.
Also, while the STL implementation is available online, it's usually risky to try and rely on the internal structure of an abstraction.
Your function shouldn't take vector<int>*
; it should take vector<int>::iterator
or vector<int>::const_iterator
as appropriate. Then, just pass in foo.begin() + 1
.
A vector is a container with full ownership of it's elements. One vector cannot hold a partial view of another, even a const-view. That's the root cause here.
If you need that, make your own container that has views with weak_ptr's to the data, or look at ranges. Pair of iterators (even pointers work well as iterators into a vector) or, even better, boost::iterator_range that work pretty seamlessly.
It depends on the templatability of your code. Use std::pair if you need to hide the code in a cpp.