Get Number of Unique Elements In Array

Hallo! I am trying to figure out how to get the number of different elements from an array. For example I need to know how many different books there are in an array, but the same book can show up throughout the array. I am using strings in structures if that is a problem. Please and thank you! I have spent a while trying to get this to work.
Well, you could sort the array, and then when looping through it check if the current book name matches the next book name, if so don't increment the uniqueElement variable and move on, then repeat, you could use one of the STD's various sorts to accomplish this, this method modifies the array so it might not be desired.

Last edited on
Maybe it is not an effective method but it works :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <set>
#include <iterator>
#include <algorithm>
#include <cstdlib>
#include <ctime>

int main()
{
	const int N = 20;
	int a[N];

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

	std::generate( std::begin( a ), std::end( a ), [] { return ( std::rand() % N ); } );

	for ( int x : a ) std::cout << x << ' ';
	std::cout << std::endl;

	std::cout << "The number of unique elements is " 
	          << std::set<int>( std::begin( a ), std::end( a ) ).size()
	          << std::endl;
}
Last edited on
Topic archived. No new replies allowed.