我有一个数组,需要将其分为 3 元素子数组。我想用迭代器来做到这一点,但最终我迭代到了数组的末尾并出现段错误即使我没有取消引用迭代器。给定:auto foo = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
我正在做:
auto bar = cbegin(foo);
for (auto it = next(bar, 3); it < foo.end(); bar = it, it = next(bar, 3)) {
for_each(bar, it, [](const auto& i) { cout << i << endl; });
}
for_each(bar, cend(foo), [](const auto& i) { cout << i << endl; });
Now I can通过定义一个来解决这个问题finish
迭代器:
auto bar = cbegin(foo);
auto finish = next(cend(foo), -(size(foo) % 3));
for (auto it = next(bar, 3); it != finish; bar = it, it = next(bar, 3)) {
for_each(bar, it, [](const auto& i) { cout << i << endl; });
}
for_each(bar, finish, [](const auto& i) { cout << i << endl; });
for_each(finish, cend(foo), [](const auto& i) { cout << i << endl; });
但这似乎没有必要我不取消引用迭代器。为什么我不能做第一个版本?