我正在尝试以下练习,但卡在了这个过程中。
Write a full program that reads in an arbitrary sequence of integers from the standard input, and writes them to the standard output in sorted order and with all duplicates removed. You may assume the input contains at most 100 integers .
我很难理解数组并试图弄清楚我需要做什么。我写下了一些代码,但我有一种强烈的感觉,我离完成它还差得很远。我不是要有人为我完成它,我只是想要一些关于如何开始的指导,或者朝着正确的方向插入。任何帮助是极大的赞赏。
#include <iostream>
using namespace std;
int main()
{
//I believe this is a start.
int numbers [100];
//declaring a counter
int i;
//making a for loop to count the integers from 1 to 100
for (i=0; i<100; i++)
{cin>>numbers[i];}
//This is the point where I got lost
if (i<100)
cout<<numbers[i]<<""<<endl;
}
最佳答案
为了对一些 int 数字进行排序,您有几种方法可以尝试其中的一些。
一种方法是当您在第一个循环中读取数据时,以这种方式将数据放在数组中的正确位置,使用另一个循环并移动新数据直到到达更小的数字。然后将新数据放在它的前面。
如果找到相同的数字,则可以忽略新数据并使用break并获取新数据。
for (i=0; i<100; i++)
{
int temp ;
cin>> temp;
int j;
for(j = i; j>= 0 ; j--)
{
if(j != 0 && number[j-1]== temp)
break ;
if(j != 0 && number[j-1] > temp)
{
number[j] = number[j-1] ;
}
else
{
number[j] = temp ;
break;
}
}
}
我认为这种方式最好,但您还有其他方式,例如: 使用类似 bubble sort 的算法对所有数字进行排序或 Quick sort 然后循环删除所有重复的数字。
int temp[100] ;
int k = 0 ;
temp[0] = number[0] ;
for(int i = 1 ; i < 100 ; i++)
{
if(temp[k] != number[i])
{
k++;
temp[k] = number[i] ;
}
关于c++ - 使用数组对整数进行排序。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22776180/