【问题标题】:C++ list iterator arithmeticC++ 列表迭代器算术
【发布时间】:2015-10-24 11:09:47
【问题描述】:

我知道您不能以“it +n”的形式使用带有列表的迭代器,但为什么当我使用 ++it 时程序能够编译,即:

//program compiles
list<int> v {1,2,3,4}; 
auto begin = v.begin(),
end = v.end(); 
while (begin != end) {
    ++begin;  
    begin = v.insert(begin, 42); 
    ++begin;  // advance begin past the element we just added
}

//program doesn't compile
list<int> v{1,2,3,4}; 
auto begin = v.begin(),
end = v.end(); 
while (begin != end) {
    begin+=1; //or alternatively begin = begin +1 
    begin = v.insert(begin, 42);  // insert the new value
    ++begin;  // advance begin past the element we just added
}

【问题讨论】:

  • 你是在问为什么标准库的设计者选择支持++begin而不是begin += n
  • 可能是因为operator++ 超载了。
  • 因为这是标准中指定list 的迭代器(bidirectional_iterator)的方式。如果你想按 n 步,递增 n 次。

标签: c++ c++11 iterator containers arithmetic-expressions


【解决方案1】:

根据标准 std::list 实现双向迭代器http://www.cplusplus.com/reference/iterator/BidirectionalIterator/ 没有“+=”运算符

【讨论】:

  • 我发现像 this one 这样的图表显示迭代器类别和它们支持的运算符很有用。
猜你喜欢
  • 2013-11-25
  • 1970-01-01
  • 2012-07-02
  • 1970-01-01
  • 1970-01-01
  • 2014-11-13
  • 2020-10-05
  • 2019-01-30
  • 2013-02-07
相关资源
最近更新 更多