swift - 在 swift 的堆栈实现中包含方法

标签 swift data-structures stack

这是我在网上找到的堆栈实现

public struct Stack<T> {
  fileprivate var array = [T]()

  public var isEmpty: Bool {
    return array.isEmpty
  }

  public var count: Int {
    return array.count
  }

  public mutating func push(_ element: T) {
    array.append(element)
  }

  public mutating func pop() -> T? {
    return array.popLast()
  }

  public var top: T? {
    return array.last
  }
}

我想要一个简单的包含方法来查看元素是否在堆栈中

最佳答案

您必须将元素标记为 Equatable检查数组中的元素是否可用。这里Stack<T : Equatable>标记 T通用元素的类型应为 Equatable .

检查这段代码:

public struct Stack<T : Equatable>
{
    fileprivate var array : [T] = [T]()

    public var count : Int { return array.count }
    public var isEmpty : Bool {return array.isEmpty }

    public mutating func push(_ element : T) {
        array.append(element)
    }

    public mutating func pop() -> T? {
        return array.popLast()
    }

    public func peek() -> T? {
        return array.last
    }

    public func contains(_ element : T) -> Bool {
        return self.array.contains { (arrayElement) -> Bool in
            return element == arrayElement
        }
    }
}

代码的使用:

// Create a stack and put some elements on it already.
var stackOfNames = Stack(array: ["Carl", "Lisa", "Stephanie", "Jeff", "Wade"])

// Add an element to the top of the stack.
stackOfNames.push("Mike")

print("Is contains : \(stackOfNames.contains("Carl"))") //true

这里我的元素是 String 的类型, 和 String已经确认输入 Equatable .所以它会起作用。

extension String : Equatable {

    /// Returns a Boolean value indicating whether two values are equal.
    ///
    /// Equality is the inverse of inequality. For any values `a` and `b`,
    /// `a == b` implies that `a != b` is `false`.
    ///
    /// - Parameters:
    ///   - lhs: A value to compare.
    ///   - rhs: Another value to compare.
    public static func ==(lhs: String, rhs: String) -> Bool
}

如果您使用自定义类型并想使用 Stack,那么您必须实现 Equatable该类的协议(protocol)。

关于swift - 在 swift 的堆栈实现中包含方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49391879/

相关文章:

ios - 在应用程序切换器菜单中暂停应用程序

c# - 用于托管语言的 Judy 数组

data-structures - 使用二叉搜索树(拉伸(stretch)树)实现 Rope 数据结构

c - 如何制作包含结构的堆栈?

ios - Swift 4 - 如何构建 json 对象并在 switch 中使用可解码(不起作用)

ios - 在 Swift 中使用引用设置 NSArray 实例

swift - 在 Swift 中从单个字符串转换为 ASCII 值的最简单方法是什么?

linux - 队列的实现给出运行时错误

c - 理解这个示例程序

objective-c - 如何从 obj-c/ios 中的堆栈跟踪获取源代码行