Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

How to create a data structure that supports insert, remove, print and get random element in C++

2 Answers

0 votes
#include <iostream>
#include <vector>
#include <map>

class Program {
public:
    std::vector<int> vec;
    std::map<int,int> mp;
    
    Program() {}
    
    bool insert(int val) {
        if (mp.find(val) == mp.end()){
            vec.push_back(val);
            mp.insert({val, vec.size() - 1});
            
            return true;
        }
        
        return false;
    }
    
    bool remove(int val) {
        if (mp.find(val) != mp.end()){
            int last = vec.back();
            
            mp[last] = mp[val];
            vec[mp[val]] = last;
            vec.pop_back();
            mp.erase(val);
            
            return true;
        }
        
        return false;
    }
    
    int getRandom() {
        int rnd = rand() % vec.size();

        return vec[rnd];
    }
    
    void print() {
        for (auto const &n: vec) {
            std::cout << n << " ";
        }
    }
};

int main()
{
    Program *p = new Program();
    
    srand(time(NULL));
    
    p->insert(6);
    p->insert(9);
    p->insert(8);
    p->insert(2);
    p->insert(1);
    
    std::cout << p->getRandom() << "\n";
    
    p->remove(2);
    
    p->print();
    
    delete p;
}




/*
run:

8
6 9 8 1

*/

 



answered Jan 28, 2024 by avibootz
0 votes
#include <iostream>
#include <vector>

class Program {
public:
    std::vector<int> vec;
    
    Program() {}
    
    void insert(int val) {
        vec.push_back(val);
    }
    
    void remove(int index) {
        int last = vec.back();

        vec[index] = last;
        vec.pop_back();
    }
    
    int getRandom() {
        int rnd = rand() % vec.size();

        return vec[rnd];
    }
    
    void print() {
        for (auto const &n: vec) {
            std::cout << n << " ";
        }
    }
};

int main()
{
    Program *p = new Program();
    
    srand(time(NULL));
    
    p->insert(6);
    p->insert(9);
    p->insert(8);
    p->insert(2);
    p->insert(1);
    
    std::cout << p->getRandom() << "\n";
    
    p->remove(2);
    
    p->print();
    
    delete p;
}




/*
run:

8
6 9 1 2 

*/

 



answered Jan 28, 2024 by avibootz
...