Caduchon
Caduchon

Reputation: 5231

Is it possible to access to a container from an iterator?

For this question, consider a simple example of a function adding values in a vector :

void insert( std::set<double>::const_iterator from_begin,
             std::set<double>::const_iterator from_end,
             std::vector<double>::iterator to )
{
  std::copy(from_begin, from_end, to);
}

Now immagine I want to add a check on the capacity of my vector, is it possible to get the container on which to works ? Is it possible to do something like that ?

void insert( std::set<double>::const_iterator from_begin,
             std::set<double>::const_iterator from_end,
             std::vector<double>::iterator to )
{
  std::vector<double>& container = give_me_the_container(to);
  assert(container.size() + std::distance(from_end,from_begin) < container.capacity());
  std::copy(from_begin, from_end, to);
}

Note: I use gcc 4.8.3. I don't use c++11 for compatibility with old gcc versions.

Upvotes: 2

Views: 535

Answers (2)

Quentin
Quentin

Reputation: 63154

Unfortunately, nothing in the iterator's API can retrieve the container. As a matter of fact, a T* is a perfectly valid implementation of std::vector<T>::iterator.

On a side note, I'm not sure what you want to guard against in this snippet. Passing in vec.end() to your function, even if the capacity is sufficient, won't work, you need std::back_inserter.

Upvotes: 4

Jarod42
Jarod42

Reputation: 218323

No, it is not possible.

(as a hint, std::vector<double>::iterator might be double*).

Upvotes: 2

Related Questions