集合的概念 在数学中,我们把具有某些共同特征的元素构成的一个整体称为集合 .一个
集合就是由同一种有序类型的一组数据元素所组成的 ,这一种有序类型称为该集合的基类 型.
课堂练****设计一个集合类 nu mSet,存放有序的整型数序,其中的元素按从小到大的顺 序排列
弁且不包含相同的元素,要求:
1)向数序中添加元素(过滤重复数据)弁保持有序
2)从数序中查找数据元素弁删除
分析:
数据成员:int count; 〃
int a[MAX]; //
成员函数: void addnum(int n); // v0id
delenum(int n); // numSet( ) {count=0;} // void disp ( ); //
测试数据: numSet set1,set2;
(3);
数序中元素的个数
存放数序的数组 向有序数组中 添加元素 从有序数组中查找元 素弁删除构造函数输出有序 数组
(2);
(1); (); (2); ();
3)求两个整数数序的合弁数序 分析:增加友元函数:
friend numSet unionset(numSet &s1, numSet &s2); 返回 s1 与 s2 合弁的结果
即:S={ s1,s2}
i=0 i<count i++
j=0 j<count j++
[i] [j] 比较确定添加顺序
例: set3=unionset(set1,set2)
set1: {1,2,3}
set2: {2,4,5,6}
set3: {1,2,3,4,5,6}
#include <iostream>
using namespace std; const int MAX=20;
class Numset
{
friend Numset unionset(Numset &s1,Numset &s2); // int count;
int a[MAX];
public:
Numset(){count=0;} void addnum(int n)
合弁数序s1和
s2
int i=0,j;
while(i<count)
if(n>a[i]) i++; else break;
// 条件合并可简化逻辑 while(i<count&&n>a[i]) i++; if(n==a[i]) return;
for(j=count;j>i;j--) a[j]=a[j-1];
a[i]=n;
count++;
}
void disp() {
for(int i=0;i<count;i++)
cout<<a[i]<<" ";
cout<<endl;
}
int geti(int i)
C 集合类 来自淘豆网www.taodocs.com转载请标明出处.