0

** 打印用户定义数组中的重复元素

//print repeated elements from an array

#include<iostream>
using namespace std;

int main()
  {
   int p,n;

   cout<<"enter no. of elements in array: "<<endl;
   cin>>n;
   int a[n],b[n];
   int z=0;
   cout<<"enter elements of array:"<<endl;
   for(int i=0;i<n;i++)
    {
        cin>>a[i];
    }
    for(int j=0;j<n;j++)
    {
        for(int k=j;k<=n;k++)
        {
            if(j==k)
            {
                continue;
            }
            else if(a[j]==a[k])
            {
                b[z]=a[j];
                ++z;
                a[k]=a[k+1];        //deleting the array element which repeats
                a[n-1]=0;           //settng last element as 0
                --n;                //reducing the size of array
                break;
            }
            int d=z;
            if(b[j]==b[k])
            {
                b[j]=b[j+1];
                b[n-1]=0;
                n--;
            }
        }
    }
    if(z==0)
    {
        cout<<"No Elemnts in the array is repeated"<<endl;
    }
    else
    {
        cout<<"repeated elements are: "<<endl;
        for(p=0;p<z;p++)
            {
                cout<<b[p]<<" ";
            }
    }

return 0;
}

如何微调该程序以显示正确的输出?当我们输入 3 个相似的元素时,它会重复两次,并且在读取最后一个元素时也有问题。谢谢

4

1 回答 1

0

你应该重写你的算法。像这样的东西应该工作:

  std::vector<int> a;

  /* fill a */

  std::sort(a.begin(), a.end());
  std::vector<int> unique_elements;
  std::unique_copy(a.begin(), a.end(), std::back_inserter(unique_elements));

  std::vector<int> b;
  std::copy_if(unique_elements.begin(), unique_elements.end(), std::back_inserter(b), [&](int n)
  {
    return std::count(a.begin(), a.end(), n) >= 2;
  });
于 2012-06-28T15:37:30.283 回答