set集合不允许重复,所以把数组元素值赋值给,set对象s, s.size()便是该数组中不重复元素的总个数, 而multiset,是允许元素值重复的,所以mutiset对象ms, ms.size()是二维数组中元素的总个数
#include<iostream> #include<set> using namespace std; /**二维数组(方阵)判断是否有重复元素,set*/ int main(int argc,char *argv[]){ int a[100][100];//创建一个大一点的数组,但输入的数据可以通过规定 阵列的行和列来输入 set<int> s;//不允许重复元素 multiset<int> ms;//可允许重复元素 int i,j; int row,clumn;//注意行列值,要小于数组的行列值100 /*21重复 5 5 35 21 21 6 13 8 3 33 15 43 9 7 11 6 16 27 26 1 24 0 4 2 25 23 24 */ /* 5 5 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 */ while(cin>>row>>clumn){ for(i=0;i<row;i++){//给二维数组赋值 for(j=0;j<clumn;j++){ cin>>a[i][j]; } } /*因为set会自动判重,重复的元素不会添加到集合中*/ s.clear(); for(i=0;i<row;i++){ for(j=0;j<clumn;j++){ s.insert(a[i][j]); } } ms.clear(); for(i=0;i<row;i++){ for(j=0;j<clumn;j++){ ms.insert(a[i][j]); } } if(s.size()!=ms.size()){//如果s集合的长度小于数组元素个数,则说明有重复元素 cout<<"该二维数组有重复元素"<<endl; }else{ cout<<"该二维数组没有重复元素"<<endl; } }//while return 0; }