溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

自定義C++ Array類以支持自定義比較

發(fā)布時(shí)間:2024-07-19 10:00:06 來源:億速云 閱讀:88 作者:小樊 欄目:編程語言
#include <iostream>
#include <vector>

template <typename T>
class Array {
public:
    Array(std::initializer_list<T> values) : m_data(values) {}

    bool operator==(const Array<T>& other) const {
        if (m_data.size() != other.size()) {
            return false;
        }

        for (size_t i = 0; i < m_data.size(); ++i) {
            if (m_data[i] != other[i]) {
                return false;
            }
        }

        return true;
    }

    bool operator!=(const Array<T>& other) const {
        return !(*this == other);
    }

    T& operator[](size_t index) {
        return m_data[index];
    }

    const T& operator[](size_t index) const {
        return m_data[index];
    }

    size_t size() const {
        return m_data.size();
    }

private:
    std::vector<T> m_data;
};

int main() {
    Array<int> arr1{1, 2, 3, 4};
    Array<int> arr2{1, 2, 3, 4};
    Array<int> arr3{1, 2, 3, 5};

    if (arr1 == arr2) {
        std::cout << "arr1 is equal to arr2" << std::endl;
    } else {
        std::cout << "arr1 is not equal to arr2" << std::endl;
    }

    if (arr1 == arr3) {
        std::cout << "arr1 is equal to arr3" << std::endl;
    } else {
        std::cout << "arr1 is not equal to arr3" << std::endl;
    }

    return 0;
}
向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI