Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a pointer to STL container an iterator is referencing?

Tags:

c++

stl

For example, the following is possible:

std::set<int> s;  
std::set<int>::iterator it = s.begin();

I wonder if the opposite is possible, say,

std::set<int>* pSet = it->**getContainer**();  // something like this...
like image 877
Jeffrey Goines Avatar asked Jul 12 '12 04:07

Jeffrey Goines


People also ask

Are STL containers passed by reference?

@BjörnPollex Yes! I forgot to mention that.

Is iterator same as pointer?

An iterator is an object (like a pointer) that points to an element inside the container. We can use iterators to move through the contents of the container. They can be visualised as something similar to a pointer pointing to some location and we can access content at that particular location using them.

How do I dereference an iterator in C++?

Dereferencing: An input iterator can be dereferenced, using the operator * and -> as an rvalue to obtain the value stored at the position being pointed to by the iterator. 4. Incrementable: An input iterator can be incremented, so that it refers to the next element in the sequence, using operator ++().

Which function is used to get a move iterator from a container?

struct vec{ iterator begin() ; const_iterator begin() const; };


2 Answers

No, there is no portable way to do this.

An iterator may not even have a reference to the container. For example, an implementation could use T* as the iterator type for both std::array<T, N> and std::vector<T>, since both store their elements as arrays.

In addition, iterators are far more general than containers, and not all iterators point into containers (for example, there are input and output iterators that read to and write from streams).

like image 164
James McNellis Avatar answered Sep 22 '22 03:09

James McNellis


No. You must remember the container that an iterator came from, at the time that you find the iterator.

A possible reason for this restriction is that pointers were meant to be valid iterators and there's no way to ask a pointer to figure out where it came from (e.g. if you point 4 elements into an array, how from that pointer alone can you tell where the beginning of the array is?).

like image 33
Kevin Grant Avatar answered Sep 25 '22 03:09

Kevin Grant