Vector容器重載運算符源碼解析

vector容器是特別有用的工具,可以完美取代數組,底層是基於數組實現的。這裏主要介紹它的重載運算符==,該運算符可以實現快速判斷兩個數組是否是一樣的。具體實現,如下代碼:

1. == 運算符重載

判斷兩個數組是一樣的,要滿足兩個條件:①兩個Vector容器的大小要一樣 ②固定位置上的值要一樣

具體運用:https://leetcode.com/problems/permutation-in-string/

//stl_vector.h
template <class T, class Alloc>
inline bool operator==(const vector<T, Alloc>& x, const vector<T, Alloc>& y) {
  return x.size() == y.size() && equal(x.begin(), x.end(), y.begin());
}
//stl_algobase.h
template <class InputIterator1, class InputIterator2>
inline bool equal(InputIterator1 first1, InputIterator1 last1,
		  InputIterator2 first2) {
  for ( ; first1 != last1; ++first1, ++first2)
    if (*first1 != *first2)
      return false;
  return true;
}

2. < 重載運算符

<重載運算符的比較過程:依次比較數組中存儲的元素的值

①若第一個數組的值小於第二個數組的值,返回true;反之,若小於,則返回false。例如[1, 2, 3] 和 [2, 3, 4] ,返回true

②若前面出現的元素的值都相等;若第一個數組的長度小於第二個數組的長度,則返回true;否則返回false

實現的源碼如下:

//stl_vector.h
template <class T, class Alloc>
inline bool operator<(const vector<T, Alloc>& x, const vector<T, Alloc>& y) {
  return lexicographical_compare(x.begin(), x.end(), y.begin(), y.end());
}
//stl_algobase.h
template <class InputIterator1, class InputIterator2>
bool lexicographical_compare(InputIterator1 first1, InputIterator1 last1,
			     InputIterator2 first2, InputIterator2 last2) {
  for ( ; first1 != last1 && first2 != last2; ++first1, ++first2) {
    if (*first1 < *first2) //比較數組中存儲的值
      return true;
    if (*first2 < *first1)
      return false;
  }
  return first1 == last1 && first2 != last2;
}

[1]《STL3.0源碼》  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章