在数组中删除和存储重复项
Removing and storing duplicates in an array
这个程序的目的是从数组中删除重复项
编写程序,从用户处输入一个包含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++习惯用法。让sort
和unique
来做重活。
#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.
相关文章:
- 使用无符号字符数组有效存储内存
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 在c++中获取两个大int,并将它们存储在数组中
- 使用 Xcode 将双精度存储在数组C++中
- 访问表示 2D 矩阵的 1D 存储数组
- 从输入文件读取整数,仅存储数组C 中的唯一整数
- 如何在队列中存储数组
- 按列主要顺序迭代行大量存储数组
- 如何使存储数组的二进制搜索稳定
- 将行中的字段从textfile中更改为存储数组,而不是重新编写文件
- 存储数组索引值C++
- 存储数组的地方,如果我在返回后声明它
- 缺少存储数组地址的内存
- 使用static在函数中存储数组各个组件的值
- 如何存储数组的每个相邻子数组的和
- 在c++中存储数组映射
- 存储数组的地址列表,以解析原始的非终止文本
- 用于存储数组的字符串
- c++存储数组下一个位置的地址
- 在 for 循环中创建和存储数组