I am trying to find unique element from the array these is question
Input : arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5}
Output : arr[] = {1, 2, 3, 4, 5}
They give me correct output but why they give 0
at the end in output:
these is my output:
{1,2,3,4,5,0}
Code:
#include<iostream>
using namespace std;
int main(){
int arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5};
int n=sizeof(arr)/sizeof(arr[0]);
int c=0;
for(int j=0;j<=n;j ){
if(arr[j]!=arr[j 1]){
cout<<arr[j];
}
}
}
CodePudding user response:
Except for std::cout
, you code is much more C than .
std::unique
of the C Standard Library does exactly what you want. There is no need to re-implement this.- Next there is the erase-remove idiom to delete the superfluous elements.
- For the output, you can use
std::for_each()
or at least a range-based for loop. - And also, you don't want
using namespace std;
A more modern solution looks like this:
#include <iostream>
#include <algorithm>
#include <vector>
int main(){
std::vector<int> arr {1, 2, 2, 3, 4, 4, 4, 5, 5};
auto last = std::unique(arr.begin(), arr.end());
arr.erase(last, arr.end());
std::for_each(arr.begin(), arr.end(), [](int n){std::cout << n << std::endl;} );
}
CodePudding user response:
problem is in for loop becouse you use less or equal to n. you need to use just less then n becouse array starts from zero that means you asking for sixth element that do not have alocalizated in memory
now it should be correct
#include<iostream>
using namespace std;
int main(){
int arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5};
int n=sizeof(arr)/sizeof(arr[0]);
int c=0;
for(int j=0;j<n;j ){
if(arr[j]!=arr[j 1]){
cout<<arr[j];
}
}
}