002.比較vector對象是否相等


1.使用vector模板

//編寫一段程序,比較vector對象是否相等 
//注:該例類似於一個【彩票游戲】


#include <iostream>
#include <ctime>    //C++標准庫,尾巴少了.h,頭部多了c
#include <cstdlib>  //C++標准庫,尾巴少了.h,頭部多了c
#include <vector>

using namespace std;

int main()
{
    const int sz = 3;     //常量sz作為vector的容量
    vector<int> V1, V2;


    //生成隨機數種子
    srand((unsigned)time(NULL));

    //通過for循環為數組元素賦值 (局部變量i,隨用隨定義)
    for (int i = 0; i != sz; i++)
    {
        //每次循環生成一個3以內的隨機數並添加到V1中
        V1.push_back(rand() % 3);
    }

    cout << "系統數據已經生成,請輸入您猜測的3個數字(0~2),可重復:" << endl;

    int uVal;//用戶輸入值

             //while (cin >> uVal) {} 最好使用for,強制把控只能輸入5個數,"cin>>uVal"依然可以用作判斷條件
    for (int i = 0; i != sz; i++)
    {
        if (cin >> uVal)
            V2.push_back(uVal);
    }
    cout << "系統生成的數據是:" << endl;
    for (auto val : V1)
    {
        cout << val << " ";
    }
    cout << endl;

    cout << "您猜測的數據是:" << endl;
    for (auto val : V2)
    {
        cout << val << " ";
    }
    cout << endl;

    //比較兩者是否相等
    auto it1 = V1.cbegin(), it2 = V2.cbegin();//令p、q分別指向數組(向量)a和b的首指針
    //注:cbegin引用不能修改原vector向量中的元素,而begin引用可以

    while (it1 != V1.cend() && it2 != V2.cend())
    {
        if (*it1 != *it2)
        {
            cout << "您的猜測有誤,兩個數組不相等" << endl;//猜錯提前結束
            return -1;
        }
        ++it1;
        ++it2;
    }
    cout << "恭喜您全部猜對了!" << endl;
    return 0;
}

 

2.使用普通數組

//編寫一段程序,比較兩個數組是否相等 
//注:該例類似於一個【彩票游戲】


#include <iostream>
#include <ctime>    //C++標准庫,尾巴少了.h,頭部多了c
#include <cstdlib>  //C++標准庫,尾巴少了.h,頭部多了c

using namespace std;

int main()
{
    //數組維度要先確定,首先需要比較維度是否相等,這里簡化問題,
    //設定兩個待比較數組的維度一致

    const int sz = 5;     //常量sz作為數組的維度
    int a[sz], b[sz];

    //生成隨機數種子
    srand((unsigned)time(NULL));

    //通過for循環為數組元素賦值 (局部變量i,隨用隨定義)
    for (int i = 0; i != sz; i++)
    {
        //每次循環生成一個10以內的隨機數並添加到a中
        a[i] = rand() % 10;
    }
    cout << "系統數據已經生成,請輸入您猜測的5個數組(0~9),可重復:" << endl;

    int uVal;//用戶輸入值

             //while (cin >> uVal) {} 最好使用for,強制把控只能輸入5個數,"cin>>uVal"依然可以用作判斷條件
    for (int i = 0; i != sz; i++)
    {
        if (cin >> uVal)
            b[i] = uVal;
    }
    cout << "系統生成的數據是:" << endl;
    for (auto val : a)
    {
        cout << val << " ";
    }
    cout << endl;

    cout << "您猜測的數據是:" << endl;
    for (auto val : b)
    {
        cout << val << " ";
    }
    cout << endl;

    //比較兩者是否相等
    int *p = begin(a), *q = begin(b);//令p、q分別指向數組a和b的首指針
    while (p != end(a) && q != end(b))
    {
        if (*p != *q)
        {
            cout << "您的猜測有誤,兩個數組不相等" << endl;//猜錯提前結束
            return -1;
        }
        ++q;
        ++p;
    }
    cout << "恭喜您全部猜對了!" << endl;
    return 0;
}

 

參考資料:

1.《C++ Primer》中文版(第五版),Stanley B.Lippman等著,電子工業出版社

2.《C++ Primer》習題集(第五版),Stanley B.Lippman等著,電子工業出版社


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM