要素を1つずつ比較していくグローバル関数を作成することになります。
template <typename T> class myvector { ... }; /** * @brief Checks if the contents of lhs and rhs are equal, that is, they * have the same number of elements and each element in lhs compares * equal with the element in rhs at the same position. * @param[in] lhs: Containers whose contents to compare in left-hand-side. * @param[in] rhs: Containers whose contents to compare in right-hand-side. * @tparam T: The type of the myvector elements. T must meet the requirements * of EqualityComparable in order to use overloads. * @return true if the contents of the containers are equal, false otherwise. */ template <class T> bool operator==(const myvector<T>& lhs, const myvector<T>& rhs) { return ( (lhs.size() == rhs.size()) && std::equal(lhs.begin(), lhs.end(), rhs.begin()) ); } /** * @brief Checks if the contents of lhs and rhs are not equal, that is, they * do not have the same number of elements or one or more elements in lhs * compares not equal with the element in rhs at the same position. * @param[in] lhs: Containers whose contents to compare in left-hand-side. * @param[in] rhs: Containers whose contents to compare in right-hand-side. * @tparam T: The type of the myvector elements. T must meet the requirements * of EqualityComparable in order to use overloads. * @return true if the contents of the containers are not equal, false otherwise. */ template <class T> bool operator!=(const myvector<T>& lhs, const myvector<T>& rhs) { return not ( (lhs.size() == rhs.size()) && std::equal(lhs.begin(), lhs.end(), rhs.begin()) ); }比較ではまず size() を比べます。これは、size() が O(1) であるので、いわゆる門前払いに有効なためです。
size() が同じであれば、std::equal() を使って、要素を一つずつ比較してきます。
全ソースコード: https://github.com/suomesta/myvector/tree/master/032
0 件のコメント:
コメントを投稿