gpt4 book ai didi

c++ - 对于 C++ 中的每个循环

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:40:32 25 4
gpt4 key购买 nike

在练习排序算法的时候,发现一个关于for each的奇怪问题。我不确定哪里出了问题,所以把整个代码贴在下面:

#include <algorithm>
#include <functional>

template <class T, class U = std::greater<>> // std::greater<> require C++14
void bubbleSort(T begin, T end, U comp = U())
{
for(auto i = end; i != begin; i--) {
for(auto j = begin; j != i; j++) {
if(comp(*j, *i)) {
std::swap(*j, *i);
}
}
}
}

template <class T, class U = std::greater<>> // std::greater<> require C++14
void bubbleSort2(T begin, T end, U comp = U())
{
auto low = begin;
auto high = end;
while(low < high) {
for(auto i = low; i != high; i++) {
if(comp(*i, *(i + 1))) {
std::swap(*i, *(i + 1));
}
}
high--;
for(auto i = high; i != low; i--) {
if(comp(*(i - 1), *i)) {
std::swap(*i, *(i - 1));
}
}
low++;
}
}

问题来了:

int main()
{
std::array<int, 10> s = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
bubbleSort(s.begin(), s.end());

for(auto i = 0; i < s.size(); i++) // Loop1
std::cout << s.at(i) << " ";

std::cout << std::endl;

for (auto a : s) { // Loop2
std::cout << a << " ";
}
return 0;
}

起初,我只写了Loop2来测试输出,但我观察到输出是:0 1 2 2 3 4 5 6 7 8。然后我添加 Loop1,输出变得正确:0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9。我认为排序函数应该有问题,但为什么添加 Loop1 可以修复它?(两种都有相同的行为)

编译器是mingw32。

感谢@FeiXiang 的评论,固定码放在GitHub

和@Aconcagua 的建议,改为:

template <class T, class U = std::greater<>> // std::greater<> require C++14
void bubbleSort3(T begin, T end, U comp = U())
{
while(end != begin) {
for(auto i = std::next(begin); i != end; ++i)
if(comp(*(i - 1), *i))
std::swap(*(i - 1), *i);
end--;
}
}

最佳答案

“i”应该从“end-1”开始

for(auto i = end-1; i != begin; i--)

因为“end”指向数组中最后一个元素的下一个位置。

关于c++ - 对于 C++ 中的每个循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51888189/

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