不使用指针进行微调

时间:2012-06-28 14:12:11

标签: c++

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

//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个相似的元素时,它会重复两次,并且在读取最后一个元素时也会遇到问题。 感谢

1 个答案:

答案 0 :(得分: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;
  });