【发布时间】:2020-07-20 20:25:18
【问题描述】:
看下面的代码
template <typename Itr>
constexpr auto foo(Itr first, Itr last)
{
for (; first != std::prev(last); std::advance(first, 1))
{
for (auto j{ first }; j != (std::prev(last) - first); std::advance(j, 1)) // Error here
{
// Do stuff
}
}
}
在第二个 for 循环中出现错误:
no operator found which takes a right-hand operand of type '__int64' (or there is no acceptable conversion)
我不允许将迭代器与 ptrdiff_t 进行比较。那么我怎样才能完成这个任务呢?我已经尝试对 j 和 ptrdiff_t 使用所有可用的演员表 - 但不允许使用任何演员表。
我需要这个的原因是,我只希望内部循环为外部循环的每次迭代迭代容器的较小子集。
我需要这个的一个例子是在冒泡排序算法的实现中
template <typename Itr>
constexpr auto bubble_sort(Itr first, Itr last)
{
for (; first != std::prev(last); std::advance(first, 1))
{
auto swapped{ false };
for (auto j{ first }; j != (std::prev(last) - first); std::advance(j, 1))
{
if (*j > *std::next(j)) // Pred
{
std::iter_swap(j, std::next(j));
swapped = true;
}
}
if (!swapped) break;
}
}
【问题讨论】:
-
您到底想在
j != (std::prev(last) - first)中比较什么?你没有真正解释你想要完成什么 -
我已经更新了问题,如果您需要更多信息,请再次评论。
-
“更小的子集”哪个更小的子集?
-
您再次没有准确解释您想要实现的目标。你的
foo函数应该做什么? -
我再次更新了问题
标签: c++ algorithm sorting templates bubble-sort