Open In App

How to Store Duplicate Elements in Ordered Set in C++?

Last Updated : 03 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The ordered set is a policy-based data structure in GNU C++ that contains unique elements in sorted order just like set. In this article, we will learn how to store duplicates in ordered set.

To store duplicates in an ordered set, use a pair data type where the first value of the pair will store the element, and the second value will store some other unique information like index or even some random number. Let’s take a look at an example:

C++
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;

// Declaring ordered_set for pair<int,int>
typedef tree<pair<int, int>, null_type, 
less<pair<int, int>>, rb_tree_tag, 
tree_order_statistics_node_update> os;

int main() {
    vector<int> v = {1, 2, 2, 1, 3};
  
  	// Creating ordered set
    os s;

    // Inserting duplicate elements in 
    // ordered set
    for (int i = 0; i < v.size(); i++)
        s.insert({v[i], i});

    for (auto i : s)
        cout << i.first << " ";
    return 0;
}

Output
1 1 2 2 3 

Explanation: In the above code, storing duplicate elements in an ordered set pair with a unique second value will make the pair different from one another.



Next Article
Article Tags :
Practice Tags :

Similar Reads