第二版 第 6 章 :  程式碼  17




解答 :
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <vector>

using namespace std ;

int main() {

    srand( static_cast<unsigned int>(time(NULL)) )  ;

    int  m , n ;

    // 隨意設定兩陣列長度  介於 [5,10]
    m = rand()%6 + 5 ;
    n = rand()%6 + 5 ;

    vector<int>  a(m) , b(n) ;
    
    int i , j ;
    
    // 隨意設定兩陣列元素值, 介於 [1,10] 
    cout << "> A : " ;
    for ( i = 0 ; i < m ; ++i ) {
        a[i] = rand()%10+1 ;
        cout << a[i] << " " ;
    }
    cout << endl ;

    cout << "> B : " ;
    for ( i = 0 ; i < n ; ++i ) {
        b[i] = rand()%10+1 ;
        cout << b[i] << " " ;
    }
    cout << endl ;

    // 重複的元素僅算一次
    cout << "> 聯集 : " ;
    for ( i = 0 ; i < m ; ++i ) {
        cout << a[i] << " " ;
        for ( j = 0 ; j < n ; ++j ) {
            if ( b[j] == a[i] ) {
                b[j] = -1 ;
                break ;
            }
        }
    }
    for ( i = 0 ; i < n ; ++i ) {
        if ( b[i] > 0 ) cout << b[i] << " " ;
    }
    

    
    
    
    cout << endl ;
    return 0 ;
    
}