In: Computer Science
I have to modify the following code to:
1. Use the unique algorithm to reduce the array to unique values
2. Use the copy algorithm to display the unique results.
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
//creating an array of 20 integers
int array[20];
//creating an empty vector
vector<int> vec;
//input from end user to get 20 ints and a for loop to interate through 20
cout << "Enter 20 integers:" << endl;
for (int i = 0; i < 20; i++) {
cin >> array[i];
}
//sorting them
sort(array, array + 20);
//using unique_copy algorithm and a back_inserter, copying and adding each
//unique value from the array to vector
unique_copy(array, array + 20, back_inserter(vec));
//displaying the unique values.
cout << "The unique values are: " << endl;
for (int i = 0; i < vec.size(); i++) {
cout << vec[i] << " ";
}
cout << endl;
return 0;
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
//creating an array of 20 integers
int array[20];
//creating an empty vector
vector<int> vec;
//input from end user to get 20 ints and a for loop to interate through 20
cout << "Enter 20 integers:" << endl;
for (int i = 0; i < 20; i++) {
cin >> array[i];
}
//sorting them
sort(array, array + 20);
// use unique algorithm to reduce array to unique value
auto it = unique(array,array+20);
// use copy algorithm
copy(array,it,back_inserter(vec));
// alternatively you can also do
// copy(array,unique(array,array+20);,back_inserter(vec));
//displaying the unique values.
cout << "The unique values are: " << endl;
for (int i = 0; i < vec.size(); i++) {
cout << vec[i] << " ";
}
cout << endl;
return 0;
}
Code screenshot:
Code output screenshot:
===============
There are two ways to do:
1)
auto it = unique(array,array+20);
copy(array,it,back_inserter(vec));
2)
copy(array,unique(array,array+20);,back_inserter(vec));
YOu can use any one.
Code along with it's output and screenshot have been added. Please refer to them
==================
For any query comment.