数据结构与算法学习库——DSA
生活随笔
收集整理的這篇文章主要介紹了
数据结构与算法学习库——DSA
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
介紹
不少在校學生在學習數據結構與算法時痛苦不堪,很多數據結構寫起來驗證也很困難。如果有一個庫,能幫助大家解決構建數據結構的困難,以快速驗證自己的想法,那多好啊。
DSA(Data struct & Algorithm) 就是這樣的一個工具。
示例 1
我們來看一個示例。
#include <iostream> #include <string_view> #include "binary_tree.h"using namespace dsa; using Tree = BinaryTree<int>;int main() {constexpr std::string_view tree_graph = R"(1 <- right_rotate/ \2 3/ \4 5||2/ \4 1/ \5 3)";// We can build a binary tree from listTree tree({1, 2, 3, 4, 5});std::cout << tree << std::endl;// Rotate at roottree.right_rotate(1);// Print the treestd::cout << tree << std::endl;return 0; }只要引入頭文件,binary_tree.h,你就能輕松的創建一個二叉樹了。創建二叉樹非常的簡單,只需要提供一個數組就行了。它的構建規則就像 leetcode 中的示例構建規則。如果你要創建一下像下面的二叉樹:
constexpr std::string_view tree_graph = R"(2/ \4 1/ \5 3 )";只需要調用:
Tree tree({2, 4, 1, {}, {}, 5, 3});其中 {}, {} 表示用于占位節點 4 的兩個空孩子節點,是不是非常簡單。整個 list 相當于對二叉樹進行層序遍歷(空節點也需要遍歷)。
當然二叉樹非常非常簡單,除此之外,你了可以引入 red_black_tree.h,來構建紅黑樹,一切都是那么的自然。
如果你想驗證自己的想法,比如想自己實現二叉樹的一些基本操作,只需要繼承 BinaryTree 就可以,像下面這樣:
class MyBinaryTree : public BinaryTree<int> { public: // ... };示例 2
下面是紅黑樹的實現:
template <typename K, typename V> class RedBlackTree : public BinarySearchTree<K, V> { public: // ... };使用起來也相當方便。
#include <vector> #include <optional> #include <red_black_tree.h>using namespace dsa;using Tree = RedBlackTree<int, int>;int main() {Tree tree;for (int i = 10; i <= 100; i += 10) {tree.insert(i, 2*i);}for (int i = 5; i <= 95; i += 10) {tree.insert(i, 2*i);}std::cout << tree << std::endl << std::endl;for (int i = 5; i <= 100; i += 5) {tree.remove(i);std::cout << "Remove:" << i << std::endl;std::cout << tree << std::endl << std::endl;}return 0; }上面的程序會輸出結果:
項目托管
本項目托管在 https://github.com/ivanallen/dsa
目前還在不斷的完善中,歡迎有志之士幫助我們提 Issue,你也可以貢獻自己的力量,來豐富這個項目。
聯系方式
- QQ 群:610441700
- 釘釘群:
總結
以上是生活随笔為你收集整理的数据结构与算法学习库——DSA的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于HASM模型的土壤高精度建模matl
- 下一篇: 判别分析在SPSS上的实现与结果分析——