【发布时间】: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