输出结果为:
The dismatching figure are 5 and 7
equal函数
该函数逐一比较两个序列的元素是否相等,返回值为true/false,不返回迭代器值。它有两个使用原型,分别为元素相等和二元谓词判断条件。
下面的实例程序用于比较两容器中数字绝对值是否相等。
#include#include #include using namespace std; int absEqual(int x, int y) { //return (x == abs(y) || y == abs(x)) 1 : 0; return abs(x) == abs(y) 1 : 0; } int main(void) { vector v1, v2; v1.push_back(3); v1.push_back(5); v1.push_back(5); v2.push_back(3); v2.push_back(5); v2.push_back(-5); if(equal(v1.begin(), v1.end(), v2.begin(), absEqual)) { cout << "The elements of v1 and v2 are equal in abosolute value." << endl; } else { cout << "The elements of v1 and v2 are not equal in abosolute value." << endl; } return 0; }
输出结果为:
The elements of v1 and v2 are equal in abosolute value.
子序列搜索算法
search函数
该函数在一个序列中搜索与另一序列匹配的子序列。它有两个使用原型,分别为完全匹配和二元谓词判断。匹配成功则返回子序列的首个元素的迭代器值。
search函数与find_first_of函数形似,但不相同。search找的是一块相同的区域,要求这块区域与后面列表的元素及其顺序相同;find_first_of找的是一个元素,只要这个元素是后面一个列表的任意一个就行。
下面的实例程序说明了search与find_first_of的不同。
#include#include #include int main(void) { vector v1, v2; v1.push_back(1); v1.push_back(4); v1.push_back(2); v1.push_back(3); v1.push_back(4); v2.push_back(2); v2.push_back(3); v2.push_back(4); vector ::iterator ivSearch, ivFind; ivSearch = search(v1.begin(), v1.end(), v2.begin(), v2.end()); ivFind = find_first_of(v1.begin(), v1.end(), v2.begin(), v2.end()); cout << "Position of search: " << ivSearch - v1.begin() << endl; cout << "Position of find_first_of: " << ivFind - v1.begin() << endl; return 0; }
输出结果为:
Position of search: 2
Position of find_first_of: 1
search_n函数
该函数用于搜索序列中是否有一系列元素值均为某个给定值的子序列。它有两个使用原型,分别为值相等和满足谓词判断条件。
下面的实例程序展示了寻找3个连续的数字8的过程。
#include#include #include using namespace std; int main(void) { vector v; v.push_back(3); v.push_back(8); v.push_back(8); v.push_back(8); v.push_back(4); vector ::iterator iv = search_n(v.begin(), v.end(), 3, 8); if(iv == v.end()) { cout << "There are no three consecutive 8." << endl; } else { cout << "Three consecutive 8 is founded." << endl; } return 0; }
结果输出为:
Three consecutive 8 is founded.
find_end函数
该函数用于在一个序列中搜索出最后一个与另一序列匹配的子序列。用search函数作用相似,方向相反。
下面的实例程序,展示了搜索容器v中最后一个与v1匹配的子序列的过程。
#include#include #include using namespace std; int main(void) { vector v, v2; v.push_back(1); v.push_back(3); v.push_back(5); v.push_back(3); v.push_back(5); v.push_back(7); v2.push_back(3); v2.push_back(5); vector ::iterator iv = find_end(v.begin(), v.end(), v2.begin(), v2.end()); if(iv != v.end()) { cout << "The position of last matching subsequence is " << iv - v.begin() << endl; } return 0; }
输出结果为:
The position of last matching subsequence is 3
小结
本文主要介绍了C++ STL算法库中的非变易算法,是一些原则上不会变更操作数据的算法,包括:
逐个查找算法:for_each元素搜索算法:find, find_if, adjacent_find, find_first_of
元素统计算法:count, count_if
序列匹配算法:dismatch, equal
子序列搜索算法:search, search_n, find_end
这些函数均包含于
参考
[1] http://www.cplusplus.com/reference/algorithm/,
[2] C++ STL开发技术导引, 叶志军, 人民邮电出版社.
(全文完)