A user specify the number of elements of ana array and then input those elements into the array. I want to display those numbers which are unique meaning not repeated. i am new to arrays so need help in the easiest of way please. The code is :
#include <iostream.h>
main()
{
int limit , i , j,counter = 0 ;
cout<<"Please enter the number of elements to be fed into the array: "; //specifying size of array
cin>>limit;
int array[limit];
cout<<"Please enter "<<limit<<" elements into array: ";
for(i=0; i<limit; i++) //array population
{
cin>>array[i];
}
cout<<"The number of unique elements in the array are: ";
for(j=0; j<limit; j++)
{
for(i=j+1; i<limit; i++)
{
if(array[j]==array[i]) //don't know what to do here to skip the duplicate values and print unique ones
}
}
}
std::swap - sort array; std::unique - gets memory address of the end of range of unique elements of this original array; print from start of the array to the location returned by std::unique:
#include <iostream>
#include <algorithm>
#include <utility>
int main()
{
size_t arySize{};
std::cout << "Array size? \n";
std::cin >> arySize;
int ary[arySize];
for (auto i = 0; i < arySize; ++i){std::cin >> ary[i];}
std::cout << "Original array \n";
for (auto i = 0; i < arySize; ++i)std::cout << ary[i] << " ";
for (auto i = 0; i < arySize; ++i)
{
for (auto j = i + 1; j < arySize; ++j)
{
if (ary[i] > ary[j])
{
std::swap(ary[i], ary[j]);
}
}
}
std::cout << "\nSorted array \n";
for (auto i = 0; i < arySize; ++i)std::cout << ary[i] << " ";
auto last = std::unique(ary, ary + arySize);
auto elements = (last - ary);//range of unique elements of the array
std::cout << "\nUnique array elements \n";
for (auto i = 0; i < elements; ++i)std::cout << ary[i] << " ";
}
please google the algorithms used and come back here if anything is unclear
finally, using standard library containers like std::vector<int> would obviously make things much simpler
edit: btw OP the header file is <iostream>, not <iostream.h>
i did got the concept upto swaping although alot of things are new to me but after that the last 3 lines before for loop didnt hit my brain.. if you can please elaborate a little what actually happend there? thanks alot
std::unique returns a forward iterator to the end of the unique range of the array which is the variable 'last' (line 27) in the previous post. Now recall that the name of an array, here ary, is a pointer (which also doubles as a forward iterator in this context) to the first element of the array. So last – ary, represented by the variable elements on line 28 of the previous post, is the number of unique elements in the array which we then proceed to print on line 30 of the program