Final answer:
To count unique integers in a vector, a C++ program uses a set to store unique elements. The set's size after insertion of all vector elements gives the number of unique integers.
Step-by-step explanation:
Counting Unique Integers in a Vector
To count the number of unique integers in a vector v, filled with random non-negative integers ranging from 0 to N-1 (inclusive), the following steps can be followed in pseudo code and C++ program.
Pseudo Code:
1. Initialize an empty set to store unique integers.
2. Iterate over each element in the vector v.
3. For each element, add it to the set.
4. The set will automatically handle duplicates, keeping only unique elements.
5. After iterating through all elements, return the size of the set.
C++ Program:
#include <iostream>
#include <vector>
#include <set>
using namespace std;
int countUniqueIntegers(const vector<int>& v) {
set<int> unique_elements;
for (int num : v) {
unique_elements.insert(num);
}
return unique_elements.size();
}
int main() {
vector<int> v = { ... }; // Vector is populated with random integers
int uniqueCount = countUniqueIntegers(v);
cout << "The number of unique integers is: " << uniqueCount << endl;
return 0;
}
This C++ program initiates by including necessary headers for iostream (input and output stream), vector, and set data structures. It defines a function countUniqueIntegers that takes a vector as an argument and returns the number of unique integers it contains. The function creates a set, iterates over the vector, and inserts each element into the set. Finally, it returns the size of the set which corresponds to the number of unique integers. The main function demonstrates how this function can be called and output displayed.