【问题标题】:given an iterator, declare an index with correct size_type给定一个迭代器,用正确的 size_type 声明一个索引
【发布时间】:2019-04-24 14:58:57
【问题描述】:

在 C++ 模板中,我很难用正确的 size_type 定义变量。基本上,这将是容器中的索引类型。我知道int 可以工作,但希望以干净的形式使用它。

template<typename ForwardIt> 
void test(ForwardIt it) {
    // this yields the underlying type
    decltype(typename std::iterator_traits<ForwardIt>::value_type()) T;

    // what I would like is something like above, but yielding the
    // correct size_type for the container.

    // Something like this but with the type extracted from ForwardIt:
    std::vector<int>::size_type i; 

    ...
}

【问题讨论】:

  • 你想用这个号码做什么?可能你想要iterator_traits&lt;It&gt;::difference_type?给定一个迭代器,通常你不能索引到容器本身(例如,它可能是一个不支持它的容器)。
  • 你可以得到difference_type。没有办法从迭代器所在的容器中获取size_type
  • @NathanOliver - 我认为您的意思是“迭代器”,而不是“容器”
  • @MarshallClow 不,我的意思是容器。 我想要的是类似上面的东西,但是为容器产生 // 正确的 size_type。

标签: c++ stl iterator decltype typename


【解决方案1】:

详细说明@NathanOliver 所说的:迭代器没有size_types;他们有一个difference_type,代表两个迭代器之间的距离。容器有一个size_type

迭代器不需要关联容器,因此无法仅从迭代器获取“容器的size_type”。

【讨论】:

  • 明确一点:当您说“迭代器不需要关联容器”时,您的意思是“......不需要关联容器type”(因为那是对应的 size_type 所绑定的),或者容器 instance?
  • 那么你最后一句话的推理是无效的。即使迭代器没有关联的容器 instance,它也有关联的容器 type,并且该容器的 size_type 应该是可获取的。
  • 我不同意。 char * 是一个迭代器。什么是容器类型?可能是vector&lt;char&gt;,可能是string,可能是array&lt;char, N&gt;,可能是某个用户定义的容器,可能是单个char。没办法说。
  • @MaxLanghof -- char ch; char* silly_iterator = &amp;ch;。没有容器,没有size_type。但是一个有效的迭代器。一个更严重的例子是std::istream_iterator&lt;char&gt; iter(std::cin);。同样,没有容器,没有size_type。容器是创建可以使用迭代器管理的序列的最常用方法,但它们不是唯一的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-03
  • 2012-11-09
  • 2011-06-30
  • 2013-03-11
  • 2012-10-23
  • 2018-06-10
  • 1970-01-01
相关资源
最近更新 更多