I am trying to write a program. It reads 5 integers between 10 and 100. As each number is read, the program validates it and stores it in the array. Then it displays the values.
I am trying to add some extra to the program. It should only store the values in the array if it is not the duplicate of a number already read. Then display only the unique numbers.
Can I get some help about how can I store and display only the unique numbers please?
Use a std::set<int>, which stores only unique elements.
When its size reaches 5 then you can either use it as your container or put the contents somewhere else.
#include <iostream>
#include <set>
usingnamespace std;
int main()
{
const size_t arraySize {5};
set<int> array1;
cout << "Please enter " << arraySize << " unique numbers between 10 and 100\n";
while (array1.size() != arraySize) {
int temporary {};
cin >> temporary;
//validate it and store it in the array
if (temporary > 10 && temporary < 100) {
if (!array1.insert(temporary).second)
cout << "Duplicate value\n";
} else
cout << "Invalid value\n";
}
cout << '\n';
for (constauto a : array1)
cout << a << '\n';
}
Returns an iterator to the first element in the range [first,last) that compares equal to val.
If no such element is found, the function returns last.
In the call std::find(array1.begin(), array1.end(), temporary) the last is array1.end().
Therefore, the value (temporary) is unique only if the std::find returns array1.end().
Furthermore, the last is after the last element. "Outside" of the array. Its value is never looked at.