gpt4 book ai didi

c++ - 使用迭代器将数组分成大小不等的部分

转载 作者:行者123 更新时间:2023-11-30 02:32:27 25 4
gpt4 key购买 nike

我有一个数组,我需要将其分成 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; });

现在我可以通过定义一个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; });

但是当我不取消对迭代器的引用 时,这似乎是不必要的。为什么我不能做第一个版本?

最佳答案

您看到的段错误来自 next 为您检查范围是调试实现中的一个断言,用于检查未定义的行为。迭代器和指针的行为未定义超出它们的分配范围,“最后一个”元素:Are iterators past the "one past-the-end" iterator undefined behavior?

这意味着递增超过“最后一个”元素是未定义的行为独立于迭代器的后续使用。为了定义行为,您必须使用类似于整数模算法或类似算法的解决方案,但您必须更改 auto it = next(bar, 3)到至少基于子数组大小的可用性进行条件化的东西,例如:auto it = size(foo) <= 3 ? finish : next(bar, 3) .

如果可用,这里最好的解决方案将导致最少的冗余迭代是跟踪容器中剩余的大小作为一个整数,当它超出范围时不会出现未定义的行为,并且“一个过去的结束”。这可以通过以下方式实现:

auto bar = cbegin(foo);

for (auto i = size(foo); i > STEP; i -= STEP) {
for(auto j = 0; j < STEP; ++j, ++bar) cout << *bar << '\t';
cout << endl;
}

for(auto i = 0; j < STEP; ++j, ++bar) cout << *bar << '\t';
cout << endl;

编辑:我之前建议使用非调试条件的指针,这是未定义的行为。

问题是 next 正在为您检查范围。我们一直在分配的内存之外使用指针,例如 nullptrend ,这就是全部 it这是。如果你只是在这里使用 C 风格的指针算法,你会没事的:

auto bar = cbegin(foo);

for (auto it = bar + 3; it < cend(foo); bar = it, it = bar + 3) {
for_each(bar, it, [](const auto& i) { cout << i << endl; });
}

for_each(bar, cend(foo), [](const auto& i) { cout << '\t' << i << endl; });

Live Example

或者,如果您在 Release 配置中运行,则应删除范围检查,这样您就可以使用代码的第一个版本。

关于c++ - 使用迭代器将数组分成大小不等的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36425393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com