在C++語言中,使用優先隊列,直接構建一個lambda運算式,使用一個匿名函數指標。java比較函數的傳回值不是bool型,只能是整型。
內部對應的C++匿名函數:
// 匿名Comparator實現
auto compareMax = []( const Cell &a, const Cell &b ) { return a.max < b.max; };
對應的Java函數:
import java.util.Queue;import java.util.Comparator;import java.util.PriorityQueue; // 匿名Comparator實現 public static Comparator<Cell> compareMax = new Comparator<Cell>() { @Override public int compare(Cell c1, Cell c2) { if (c1.max < c2.max) return 1; else return -1; } };
匿名比較函數實現,java使用int型,傳回值為1和-1,C++可以使用boolean型。其實應該寫一個lambda運算式的
Java優先隊列的使用:
Queue<Cell> cellQueue = new PriorityQueue( compareMax );
對應C++ 優先隊列的使用:
using Queue = std::priority_queue< Cell<T>, std::vector<Cell<T> >, decltype(compareMax)>;Queue<Cell> cellQueue = new PriorityQueue(compareMax);
實現功能,在插入時,可以使用c.max進行排序插入。
參考:java函數式編程之lambda運算式
匿名類實現匿名函數:
public void testAnonymousClass() { Integer[] nums = {2, 5, 1, 6}; Arrays.sort(nums, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { if(o1 < o2) return -1; return 0; } }); for (Integer n : nums) { System.out.println(n); }}
lambda 運算式:
public void testAnonymousClass() { Integer[] nums = {2, 5, 1, 6}; Arrays.sort(nums, (o1, o2) -> { if(o1 < o2) return -1; return 0; }); for (Integer n : nums) { System.out.println(n); }}
參考:java中queue的使用
Queue介面與List、Set同一層級,都是繼承了Collection介面。LinkedList實現了Queue接 口。Queue介面窄化了對LinkedList的方法的存取權限(即在方法中的參數類型如果是Queue時,就完全只能訪問Queue介面所定義的方法 了,而不能直接存取 LinkedList的非Queue的方法),以使得只有恰當的方法才可以使用。BlockingQueue 繼承了Queue介面。
add 增加一個元索 如果隊列已滿,則拋出一個IIIegaISlabEepeplian異常
remove 移除並返回隊列頭部的元素 如果隊列為空白,則拋出一個NoSuchElementException異常
element 返回隊列頭部的元素 如果隊列為空白,則拋出一個NoSuchElementException異常
offer 添加一個元素並返回true 如果隊列已滿,則返回false
poll 移除並返問隊列頭部的元素 如果隊列為空白,則返回null
peek 返回隊列頭部的元素 如果隊列為空白,則返回null
put 添加一個元素 如果隊列滿,則阻塞
take 移除並返回隊列頭部的元素 如果隊列為空白,則阻塞
remove、element、offer 、poll、peek 其實是屬於Queue介面。
參考:java8 手把手教你學會寫lambda運算式