Better way to remove random duplicates?

I was wondering if my way of removing duplicates is bad in any way.. If there's a better way of doing it please explain thanks! I can also use this for a Word Jumble game so that the same words don't come up again, anyways post away.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  int main()
{

	srand((unsigned int)time(0));

	std::vector<int> randomNumbers;
	std::vector<int>::const_iterator cIter;
	randomNumbers.reserve(10);

	const int MAX_ELEMENTS = 10;
	for (unsigned int i = 0; i < MAX_ELEMENTS; ++i)
	{
		int randNumber = (rand() % 10) + 1;
		while (std::count(randomNumbers.begin(), randomNumbers.end(), randNumber) > 0)
		{
			randNumber = (rand() % 10) + 1;
		}
		randomNumbers.push_back(randNumber);
	}

	for (cIter = randomNumbers.begin(); cIter != randomNumbers.end(); ++cIter)
		cout << *cIter << endl;

	return 0;
}
closed account (Dy7SLyTq)
isnt there like a unique_copy function in algorithim?
You could use std::set for this instead.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <windows.h>
#include <ctime>
#include <iostream>
#include <set>

int main(int argc, char* argv[]) {
	const unsigned short size = 10;
	std::set<unsigned short> container;
	srand(time(0));
	for(unsigned short i=0; i<size; ++i) {
		container.insert(rand()%size);
	}
	for(std::set<unsigned short>::iterator it=container.begin(); it!=container.end(); ++it) {
		std::cout << *it << std::endl;
	}
	std::cin.get();
	return 0;
}


One property of the std::set is that it only holds unique elements.
Last edited on
Thank you xismn! I never used set before and btw why don't you declare the data type to unsigned short int, wouldn't it make it more clear? Thanks for your knowledge :)
Last edited on
closed account (Dy7SLyTq)
unsigned short and unsigned short int are the same thing
Yes, I know but I still prefer to use int my self but okay. Also the std::set doesn't fully work with what I was trying to do. It seems like it removes the none unique numbers but I want it to roll it 10 times randomly 1-10 and not in order too.
create array of elements 1-10 and apply random_shuffle to it.
http://www.cplusplus.com/reference/algorithm/random_shuffle/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream> 
#include <algorithm> 
#include <vector>   

int main () 
{
  std::vector<int> myvector = {1, 2, 3, 4, 5, 6, 7, 8 ,9, 10};

  std::random_shuffle(myvector.begin(), myvector.end());

  // print out content:
  std::cout << "myvector contains:";
  for (auto i: myvector)
    std::cout << ' ' << i;

  std::cout << '\n';

  return 0;
}
myvector contains: 9 2 10 3 1 6 8 4 5 7
Last edited on
Topic archived. No new replies allowed.