Policy based data structures in g++

The g++ compiler also supports some data structures that are not part of the C++ standard library. Such structures are called policy-based data structures. These data structures are designed for high-performance, flexibility, semantic safety, and conformance to the corresponding containers in std.

To use these structures, the following lines must be added to the code:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


For an example following is a code showing a policy-based data structure that is like set, it can add/remove elements, can find the number of elements less than x, kth smallest element etc in O(logn) time. It can also be indexed like an array. The specialty of this set is that we have access to the indices that the elements would have in a sorted array. If the element does not appear in the set, we get the position that the element would have in the set.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Program showing a policy-based data structure.
#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp>
#include <functional> // for less
#include <iostream>
using namespace __gnu_pbds;
using namespace std;
  
// a new data structure defined. Please refer below
// GNU link : https://goo.gl/WVDL6g
typedef tree<int, null_type, less<int>, rb_tree_tag,
             tree_order_statistics_node_update>
    new_data_set;
  
// Driver code
int main()
{
    new_data_set p;
    p.insert(5);
    p.insert(2);
    p.insert(6);
    p.insert(4);
  
    // value at 3rd index in sorted array.
    cout << "The value at 3rd index ::" 
         << *p.find_by_order(3) << endl;
  
    // index of number 6
    cout << "The index of number 6::" 
         << p.order_of_key(6) << endl;
  
    // number 7 not in the set but it will show the 
    // index number if it was there in sorted array.
    cout << "The index of number seven ::"
         << p.order_of_key(7) << endl;
  
    return 0;
}

chevron_right


Output:

The value at 3rd index ::6
The index of number 6::3
The index of number seven ::4

NOTE:Both the functions order_of_key and find_by_order work in logarithmic time.



My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


5


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.