【发布时间】:2020-11-12 08:33:09
【问题描述】:
前;
我们写for(int i=0;i<(somethin_length)-1;i++)
如何使用 set 来做到这一点?
【问题讨论】:
-
但是你想对除了最后一个元素之外的所有元素做一些事情,还是你想对倒数第二个元素做一些事情?在第二种情况下......反向迭代器(
rbegin())呢?
前;
我们写for(int i=0;i<(somethin_length)-1;i++)
如何使用 set 来做到这一点?
【问题讨论】:
rbegin())呢?
如果你有一个集合,只需将结束迭代器递减两次。
// Check that we have at least two elements first; if we don't have at least
// two then proceeding would cause undefined behavior.
if (some_set.size() >= 2) {
auto it = some_set.end();
--it;
--it;
// *it now refers to the second-to-last value
}
【讨论】:
auto it = std::prev(some_set.end(), 2);。
auto it = std::next(some_set.end(), -2);
auto it = some_set.rbegin(); ++it;
it 用作上限,我想你是对的。顺便说一句,您可以在 std::prev 中省略 1。