In: Computer Science
1. Read 20 integers into an array. Next, use the unique algorithm to reduce the array to the unique values entered by the user. Use the copy algorithm to display the unique values.
2. Modify the Exercise 1 above to use the unique_copy algorith. The unique values should be inserted into a vector that's initially empty. Use a back_inserter to enable the vector to grow as new items are added. Use the copy algorithm to display the unique values.
Solution:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
//creating an array of 20 integers
int arr[20];
//creating an empty vector
vector<int> v;
//input 20 integers and a for loop to interate
cout << "Enter 20 integers:" << endl;
for (int i = 0; i < 20; i++) {
cin >> arr[i];
}
//sorting them
sort(arr, arr + 20);
// using stl unique algorithm to reduce array to unique values
auto it = unique(arr,arr+20);
// Way 1:using copy algorithm
copy(arr,it,back_inserter(v));
// Way 2:Or You can also do
// copy(arr,unique(arr,arr+20);,back_inserter(v));
//displaying unique values.
cout << "The unique values are: " << endl;
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
cout << endl;
return 0;
}