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

51,813 answers

573 users

How to get random value and insert a value into 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;
    }

    int getRandom() {
        int r = rand() % vec.size();
        return vec[r];
    }
};

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




/*
run:

18
3

*/

 



answered Jul 8, 2023 by avibootz

Related questions

1 answer 205 views
3 answers 138 views
3 answers 146 views
1 answer 169 views
...