區間比較演算法
(1)equal()
該函式可以實現兩個容器物件的比較,如果兩個物件相等,函式返回true,只能比較屬於同一型別的不同變數。
template bool equal (inputiterator1 first1, inputiterator1 last1,inputiterator2 first2);
template bool equal (inputiterator1 first1, inputiterator1 last1,inputiterator2 first2, binarypredicate pred);
template bool equal ( inputiterator1 first1, inputiterator1 last1, inputiterator2 first2 )
return true;
}
用法示例:
#include #include // std::equal
#include bool mypredicate(int i, int j)
int main() ;
std::vectormyvector(myints, myints + 5); // myvector: 20 40 60 80 100
if (std::equal(myvector.begin(), myvector.end(), myints))
std::cout << "the contents of both sequences are equal.\n";
else
std::cout << "the contents of both sequences differ.\n";
myvector[3] = 81; // myvector: 20 40 60 81 100
if (std::equal(myvector.begin(), myvector.end(), myints, mypredicate))
std::cout << "the contents of both sequences are equal.\n";
else
std::cout << "the contents of both sequences differ.\n";
return 0;
}
#include #include #include using namespace std;
bool relationship(int e1, int e2)
void print(vector& v)
void main()
; int arr2 = ;
vectorv1(arr1, arr1 + 7);
vectorv2(arr2, arr2 + 7);
cout << "vector v1: " << endl;
print(v1);
cout << "vector v2: " << endl;
print(v2);
bool eq = equal(v1.begin(), v1.end(), v2.begin());
if (eq)
else
bool eq2 = equal(v1.begin(), v1.end(), v2.begin(), relationship);
if (eq2)
else
}
(2)mismatch()用於尋找兩個容器物件之間兩兩相異的對應元素,如果沒有找到相異點,也並不代表兩個物件完全相同,因為兩個物件的容量不一定相同。要判斷相同,就要使用equal演算法。如果沒有找到相異點,函式返回乙個pair,以第乙個物件的end元素和第二個物件的對應元素組成。如果找到相異點,則相異點的對應元素組成乙個pair,並返回
template pairmismatch (inputiterator1 first1, inputiterator1 last1,inputiterator2 first2);
template pairmismatch (inputiterator1 first1, inputiterator1 last1,inputiterator2 first2, binarypredicate pred);
template pairmismatch (inputiterator1 first1, inputiterator1 last1, inputiterator2 first2 )
return std::make_pair(first1,first2);
}
用法示例:
#include #include #include #include using namespace std;
void print(int& ele)
void main()
; int arr2 = ;
listl1(arr1,arr1+6);
vectorl2(arr2,arr2+6);
pair::iterator, vector::iterator> p1;
for_each(l1.begin(), l1.end(), print);
cout << endl;
for_each(l2.begin(), l2.end(), print);
cout << endl;
p1 = mismatch(l1.begin(), l1.end(), l2.begin());
if (p1.first == l1.end())
else
p1 = mismatch(l1.begin(), l1.end(), l2.begin(), less_equal());
if (p1.first == l1.end())
else
}
ACM學習歷程4 STL的使用
在演算法設計大賽中,會使用一些語言本身提供的庫,在這些庫裡面包含了大量已經實現了的資料結構或者演算法,我們是需要在使用的過程中加入響應的標頭檔案即可使用。標準模板庫 standard template library 是ansi iso c 最有特色 最實用的部分之一。stl包含了容器類 conta...
幾種常見的查詢演算法之比較
一 順序查詢 條件 無序或有序佇列。原理 按順序比較每個元素,直到找到關鍵字為止。時間複雜度 o n 二 二分查詢 折半查詢 條件 有序陣列 原理 查詢過程從陣列的中間元素開始,如果中間元素正好是要查詢的元素,則搜素過程結束 如果某一特定元素大於或者小於中間元素,則在陣列大於或小於中間元素的那一半中...
幾種STL排序演算法比較
接著上一回的說,對 stl幾種排序演算法做一比較,比較並不全面,僅僅對 std sort std stable sort c 標準庫qort 和std heap sort 做一比較,因為這是用的最多的,其底層實現已足夠說明日常生活中排序問題所需要考慮的問題。程式 如下 1 2 3 45 6 7 89...