I have a
n elements. Now I need to pass a pointer to a vector that has the last
n-1 elements to a function.
For example, my
vector<int> foo contains
(5,2,6,87,251). A function takes
vector<int>* and I want to pass it a pointer to
Can I just (safely) take the iterator
++foo.begin(), convert it to a pointer and pass that to the function? Or use
UPDATE: People suggest that I change my function to take an iterator rather than a pointer. That seems not possible in my situation, since the function I mentioned is the
find function of
unordered_set<std::vector*>. So in that case, is copying the
n-1 elements from
foo into a new vector and calling
find with a pointer to that the only option? Very inefficient! It's like Shlemiel the painter, especially since i have to query many subsets: the last
n-2, etc. elements and see if they are in the
That seems not possible in my situation, since the function I mentioned is the find function of
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.
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
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.
here it is, obtaining a reference to the coresponding pointer of an iterator use :
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].