前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >类模块——接口排序

类模块——接口排序

作者头像
xyj
发布2020-07-28 11:28:29
2840
发布2020-07-28 11:28:29
举报
文章被收录于专栏:VBA 学习VBA 学习

能用好类与接口的话,代码的复用率会非常高,是个值得好好学习的东西。

用排序功能来举例,排序是经常使用到的,比如冒泡排序:

Sub BubbleSort(l())
    Dim i As Long, j As Long

    For i = 1 To UBound(l)
        For j = i + 1 To UBound(l)
            If l(i) > l(j) Then
                Call Swap(l, i, j)
            End If
        Next j
    Next i
End Sub

Function Swap(l(), Low As Long, High As Long)
    Dim iTemp
    iTemp = l(Low)
    l(Low) = l(High)
    l(High) = iTemp
End Function

有了这个函数,只要传入1个一维数组,函数执行完后数组就有序了。 但是,如果需要排序的是个二维数组的话,就不得不把排序函数重新写过一次,如果是结构体,又得重新写过…… 接口的使用,就可以最小化的来修改这些东西。 对于这个排序函数,不管传入的是什么数据,排序算法是固定的,不同的地方是:

  • 2个数据的比较 (If l(i) > l(j) Then)
  • 2个数据的交换 ( Swap)

排序算法是固定的,要修改的是这2个功能,只要传入的东西里面具有这2个功能就可以了,具有功能的东西,也就是类,类能有自己的方法。 但是又不能传入某种具体的类,因为数据的不同,这2个方法也是不相同的,这就需要接口了。接口ISort定义2个功能:

Function Swap(i As Long, j As Long)

End Function

Function Less(i As Long, j As Long) As Boolean

End Function

然后排序函数传入的是这个接口:

Sub BubbleSort(I_Sort As ISort, Low As Long, High As Long)
    Dim i As Long, j As Long

    For i = Low To High
        For j = i + 1 To High
            If I_Sort.Less(j, i) Then
                I_Sort.Swap i, j
            End If
        Next j
    Next i
End Sub

一维数据的实现:

Implements ISort

Private arr() As Variant

Property Let Data(Value As Variant)
    arr = Value
End Property
Property Get Data() As Variant
    Data = arr
End Property

'比较
Private Function ISort_Less(i As Long, j As Long) As Boolean
    ISort_Less = arr(i) < arr(j)
End Function

'交换
Private Function ISort_Swap(i As Long, j As Long) As Variant
    Dim tmp As Variant

    tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
End Function

二维数组实现接口:

Implements ISort

Private Type LowHigh
    Low As Long
    High As Long
End Type

Private arr() As Variant
Private i_col As Long           '要排序的列
Private Col_Bound As LowHigh    '列的上下标

Property Let SortCol(iCol As Long)
    i_col = iCol
End Property

Property Let Data(Value As Variant)
    arr = Value
    
    Col_Bound.Low = LBound(arr, 2)
    Col_Bound.High = UBound(arr, 2)
End Property
Property Get Data() As Variant
    Data = arr
End Property

'比较
Private Function ISort_Less(i As Long, j As Long) As Boolean
    ISort_Less = arr(i, i_col) < arr(j, i_col)
End Function

'交换
Private Function ISort_Swap(i As Long, j As Long) As Variant
    Dim tmp As Variant
    Dim k As Long
    
    For k = Col_Bound.Low To Col_Bound.High
        tmp = arr(i, k)
        arr(i, k) = arr(j, k)
        arr(j, k) = tmp
    Next k
End Function
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-05-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 VBA 学习 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档