g++ 中基於策略的資料結構


g++ 編譯器是 GNU Linux 中的 C++ 編譯器。

g++ 編譯器還為 C++ 程式語言標準庫中沒有的一些特殊資料結構添加了支援。這些稱為策略資料結構。

策略資料結構為程式設計師提供了高效能、語義安全性和靈活性,而 C++ std 庫的標準資料結構則無法提供。

若要將這些資料結構包含到程式中,應新增以下幾行:

#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;

示例

我們來看一個程式,瞭解這些策略資料結構如何工作。

 線上演示

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <functional>
#include <iostream>
using namespace __gnu_pbds;
using namespace std;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>
new_data_set;
int main() {
   new_data_set data;
   data.insert(34);
   data.insert(785);
   data.insert(12);
   data.insert(87);
   cout<<"The value at index 2 is "<<*data.find_by_order(2)<<endl;
   cout<<"The index of number 87 is "<<data.order_of_key(87)<<endl;
   return 0;
}

輸出

The value at index 2 is 785
The index of number 87 is 4

這些資料結構非常通用,你可以執行許多功能,例如檢查元素索引、查詢索引中的元素等。

更新日期:2020 年 4 月 17 日

299 次瀏覽

開啟你的事業

透過完成課程獲得認證

開始
廣告