how do i insert randomized elements inside a vector without repeating elements?
i came about this article that I thought would help me but i think I'm implementing incorrectly?
ElusiveTau is correct, including the proper header is the correct and portable method. It's not safe to assume other standard headers implicitly include <algorithm>.
#include <iostream>
#include <vector>
#include <algorithm>
usingnamespace std;
int random_number(int lo, int hi)
{
return rand() % (hi - lo) + lo;
}
int main()
{
srand(time(nullptr));
vector<int> v;
for (int i = 0; i < 100; ++i)
{
int r = random_number(1, 100);
if (count(v.begin(), v.end(), r))
i -= 1;
else
v.push_back(r);
};
cout << "Random List\nBEFORE SORT: ";
for (auto& i : v)
cout << i << ' ';
cout << '\n';
sort(v.begin(), v.end());
cout << "AFTER SORT: ";
for (auto& i : v)
cout << i << " ";
cout << '\n';
}
Problem is, your algorithm is too slow to be practical. The first non-duplicate random number is always chosen on the first try. But when it's time to insert the last non-duplicate number, that one will only be chosen with 1% probability. Each time a guess is taken, the entire vector must be checked to look for a duplicate.