Count the number of unique elements in a vector in C++

Given a vector in C++, the task is to find the number of distinct elements present in the vector.

Example:

Input:  v={ 16, 10, 9, 25, 2, 16, 10, 9 }

Output: 5

Explanation: There are five distinct elements 16, 10, 9, 25, and 2.

There are two different methods by which we can solve this problem.

1. Using two for loops.

2. Using sorting.

We will understand each method with the help of code.

1. Using two for loops

Create a variable count and run two for loops, first with counter i ranging from 0 to v.size()-1 to traverse the vector. The second loop will run from counter j ranging from 0 to i-1 to check if the element has occurred before or not. If v[i]==v[j] break from the loop and if i==j increment the count.

Let’s understand this with help of code:

#include <iostream>
#include<vector>
using namespace std;

int main()
{
    vector<int> v={ 16, 10, 9, 25, 2, 16, 10, 9 };
    
    int count = 1; // counting the first element as distinct

    for (int i = 1; i < v.size(); i++) {
        int j = 0;
        for (j = 0; j < i; j++)
            if (v[i] == v[j])
                break;

            if (i == j)
            count++;
    } 
    cout<<count;
    return 0;
}
Output:
5

2. Using sorting

Sort the given vector using sort(v.begin(),v.end()). After sorting, all occurrences of every element become consecutive. Traverse the vector and count the distinct elements by comparing the consecutive elements.

Let’s understand this with code:

#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main()
{
    vector<int> v={ 16, 10, 9, 25, 2, 16, 10, 9 };
    sort(v.begin(), v.end());  //sort the vector
    int count = 0;
    for (int i = 0; i < v.size(); i++) {
        while (i < v.size() - 1 && v[i] == v[i + 1])
        {
         i++;
        }
      count++;
    } 
    cout<<count;
    return 0;
}
Output:
5

Leave a Reply

Your email address will not be published. Required fields are marked *