首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >实现基于迭代器的shell排序

实现基于迭代器的shell排序
EN

Stack Overflow用户
提问于 2013-09-06 20:37:33
回答 2查看 681关注 0票数 0

我的外壳排序如下:

代码语言:javascript
复制
template<class T>
void shellSort(T *begin, T *end) {
    int shell = 1;

    while (shell < (begin - end) / 3) shell = shell * 3 + 1;
    while (shell > 0) {
        for (auto index = shell; index < end; index++) {
            for (auto insertion = index; insertion >= shell && *(insertion - shell) > *(insertion); insertion -= shell) {
                swap(*(insertion - shell), *(insertion));
            }
        }

        shell = shell / 3;
    }
}

磨坊运转得很好。我遇到的问题就在这条线上:

代码语言:javascript
复制
for (auto index = shell; index < end; index++)

因为shell是一个int,但是end是一个int *,所以它不知道如何进行比较。我该怎么解决这个问题?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-09-06 20:43:37

使用“迭代器”寻址项,只对相对偏移量使用整数:

代码语言:javascript
复制
for (auto index = begin + shell; index < end; ++index) ...

顺便说一句,您可能需要shell < (end - begin)/3,而不是(begin - end)

票数 1
EN

Stack Overflow用户

发布于 2013-09-06 20:48:32

假设这些是随机访问迭代器,否则性能将非常糟糕。

您可以使用std::distance来获得两个迭代器之间的区别。还可以使用std::advance向迭代器添加整数。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18666209

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档