是否可以从迭代器访问容器?

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

对于这个问题,考虑一个在向量中添加值的函数的简单示例:

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);
}

想象一下,我想检查我的向量的容量,是否可以获取 to 工作的容器? 是否可以做那样的事吗?

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);
}

注意:我用的是gcc 4.8.3。 为了与旧的 gcc 版本兼容,我不使用 c++11

不,不可能。

(作为提示,std::vector<double>::iterator 可能是 double*)。

不幸的是,迭代器的 API 中没有任何内容可以检索容器。事实上,T*std::vector<T>::iterator.

的完全有效实现

附带说明一下,我不确定您要在此代码段中防范什么。给你的函数传入vec.end(),即使容量够用也不行,你需要std::back_inserter