在数组中删除和存储重复项

Removing and storing duplicates in an array

本文关键字:存储 数组 删除      更新时间:2023-10-16

这个程序的目的是从数组中删除重复项

编写程序,从用户处输入一个包含10个整数的数组,并删除重复的数组元素。

下面是一些示例输出:请输入10个整数,每一个后按回车键:5751075580105550您输入了5个唯一的数字:5 75 10 80 50

这是我到目前为止的代码

#include <iostream>
using namespace std;
int main()
{
int myint[11];
int i,x,count=10;
cout << "Please input 10 integers, hitting return after each one n";
    for(i=0;i<10;i++){
    cin>> myint[i];
    }
    for(i=0;i<=10;i++)
    {
            for(x=i+1;x<=10;x++)
            {
                    if(myint[x]==myint[i])
                    {
                            count--;
                            for(i=x;i<=count;i++)
                            { myint[i] = myint[i+1];
                            }
                    }
            }
      }
cout << endl;
cout << " You entered "<< count << " unique numbers: " <<  endl;
    for(i=0;i<count;i++){
    cout << myint[i] << " ";
    }
return 0;
}

是我的输出请输入10个整数,每输入一个后按回车键5751075580105550

您输入了7个唯一的数字:5 75 10 75 80 10 5

必须删除或重写重复的数字,唯一的数字应该放在一个新的数组中,而不仅仅是显示在屏幕上。我不完全确定我的错误在哪里。似乎在某个地方,第一次循环运行时,它似乎找到了一个重复的,无论如何,并抛出了数组中循环的其余部分?我有点迷路了。任何帮助都是感激的。谢谢。

既然问题被标记为c++,那么您也可以在代码中使用c++习惯用法。让sortunique来做重活。

#include <iostream>
#include <vector>
using namespace std;
int main(int argc, const char * argv[])
{
   vector<int> v;
   cout << "Please input 10 integers, hitting return after each one n";
   for( int i = 0; i < 10; i++ ) {
      int num;
      cin >> num;
      v.push_back(num);
   }
   sort( v.begin(), v.end() );
   v.erase( unique( v.begin(), v.end() ), v.end() );
   cout << endl << " You entered " << v.size() << " unique numbers: " <<  endl;
   copy( v.begin(), v.end(), ostream_iterator<int>( cout, " " ) );
}

这是我在@chr的解决方案中提到的set的解决方案:

#include <iostream>
#include <set>
#include <algorithm>
#include <iterator>
using namespace std;
int main(int argc, const char* argv[])
{
   set<int> s;
   cout << "Please input 10 integers, hitting return after each one n";
   for( int i = 0; i < 10; i++ ) {
      int num;
      cin >> num;
      s.insert(num);
   }
   cout << endl << " You entered " << s.size() << " unique numbers: " <<  endl;
   copy( s.begin(), s.end(), ostream_iterator<int>( cout, " " ) );
}

最内层循环重用最外层循环的变量i。用另一个字母代替

同样奇怪的是,如果你想读取10个元素,为什么你有一个数组和对应的11个循环。此外,您可以使用<= 10.