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,845 questions

51,766 answers

573 users

How to get random value, insert and remove values from a vector if not exists in C++

1 Answer

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

class ASet {
public:
    std::vector<int> vec;
    ASet() {
        srand(time(NULL));
    }
    
    bool insert(int val) {
        if (find(vec.begin(), vec.end(), val) == vec.end()) {
            vec.push_back(val);
            return true;
        }
        return false;
    }
    
    bool remove(int val) {
        if (find(vec.begin(), vec.end(), val) != vec.end()) {
            vec.erase(std::remove(vec.begin(), vec.end(), val), vec.end());
            return true;
        }
        return false;
    }
    
    int getRandom() {
        int r = rand() % vec.size();
        return vec[r];
    }

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

int main()
{
    ASet* st = new ASet();
    
    st->insert(99);
    st->insert(3);
    st->insert(6);
    st->insert(1);
    st->insert(28);
    st->insert(19);
    
    st->print();
    
    std::cout << "\n" << st->getRandom() << "\n";

    st->remove(3);
    st->remove(28);

    std::cout << "\n";
    st->print();
    
    std::cout << "\n" << st->getRandom() << "\n";

    delete st;
}




/*
run:

99 3 6 1 28 19 
6

99 6 1 19 
19

*/

 



answered Jul 8, 2023 by avibootz
...