c++ - 优先队列 Objective-C++?

标签 c++ ios objective-c priority-queue

我正在研究一种路径查找算法,并希望实现一个优先级队列来加快速度。

我正在根据属性 fScore 将我的 Node 对象添加到队列中。最小的 fScore 总是被添加到队列的顶部。

我对此有哪些选择?最好使用 STL 实现 c++ 优先级队列吗?如果是这样,我将如何设置它以接收我的 objective-c 对象 Node 以及我将如何指定列表的排序依据 (Node.fScore)。

谢谢

最佳答案

对于 std::priority_queue,如果您使用的是 ARC,那么您应该已经完成​​了 90%。 STL 容器会自动存储强引用。赢了!

您需要创建一个自定义比较类。

typedef std::priority_queue<MyClass *, std::vector<MyClass *>, MyClassCompare> MyPriorityQueue;

我不确定您将如何实现您的比较类。它看起来像:

class MyClassCompare {
    bool operator()(MyClass *lhs, MyClass *rhs) const {
        // magic!!! Be sure to return a bool.
    }
};

示例包装器类

MyClassQueue.h

@interface MyClassQueue : NSObject
@property (nonatomic, readonly) MyClass *topObject;
@property (nonatomic, readonly) NSUInteger count;
- (void)pushObject:(MyClass *)myObject;
- (void)popObject;
- (void)popAllObjects;
@end

MyClassQueue.mm

#import "MyClassQueue.h"
#include <queue>
#import "MyClass.h"

class MyClassCompare {
    bool operator()(MyClass *lhs, MyClass *rhs) const {
        // magic!!! Be sure to return a bool.
    }
};

typedef std::priority_queue<MyClass *, std::vector<MyClass *>, MyClassCompare> MyPriorityQueue;

@interface MyClassQueue ()
@property (nonatomic) MyPriorityQueue *queue;
@end
@implementation MyClassQueue

- (MyClass *)topObject {
    return !self.queue->empty() ? self.queue->top() : nil;
}

- (NSUInteger)count {
    return (NSUInteger)self.queue->size();
}

- (void)pushObject:(MyClass *)myObject {
    self.queue->push(myObject);
}

- (void)popObject {
    if (!self.queue->empty()) {
        self.queue->pop();
    }
}

- (void)popAllObjects {
    if (!self.queue->empty()) {
        delete _queue;
        _queue = new MyPriorityQueue();
    }
}

- (instancetype)init {
    self = [super init];
    if (self != nil) {
        _queue = new MyPriorityQueue();
    }
    return self;
}

- (void)dealloc {
    delete _queue;
    _queue = NULL;
}    
@end

关于c++ - 优先队列 Objective-C++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20820911/

相关文章:

c++ - 对继承的 vtable 的 undefined reference

c++ - Ad-Hoc网络控制

iphone - 以编程方式设置 UITabBar 标题

objective-c - 在 Swift 中实现的 Objective-C 回调

c++ - 嵌入式 Python 无法使用 NumPy 指向 Python35.zip - 如何修复?

c++ - 在运行时动态组合 Boost.Spirit.Qi 规则(任意数量的备选方案)

ios - SpriteKit 电池/能量消耗

ios - SLComposeViewController Facebook 发布为 iOS 而不是 Facebook 应用程序标识符

iphone - 为什么在创建 UIWebView 时清除 NSUserDefaults 会导致 EXC_CRASH?

objective-c - IOS中的即时/自动保存