后面的几篇博客会讲STL的算法,本文主要讲:
equal()函数用来比较两个序列的值是否相同?如果两个序列的长度不同,则equal()返回false。==运算符用于进行比较操作。还有另外一个版本的equal,使用一个二元谓词函数作为第四个参数,估计是比较复杂,本例子并没有包含这个版本的equal()。
mismatch()函数比较两个序列的值并返回一个pair对象,pair中的两个迭代器表明两个序列中不匹配的元素所在的位置。
lexicographical_compare()函数会检测第一个序列中的元素是否比第二个序列中的小?如果小,就返回true,如果大或者相等,就返回false。
代码如下:
// Fig22_27_STL_Algor_equal_mismatch_lexicographical_compare.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//Standard library functions equal, mismatch and lexicographical_compare
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
// std::cout << "Hello World!\n";
const int SIZE = 10;
int a1[SIZE] = {1,2,3,4,5,6,7,8,9,10};
int a2[SIZE] = { 1,2,3,4,1000,6,7,8,9,10 };
vector <int> v1(a1,a1 + SIZE);//copy of a1,通过数组地址初始化vector
vector <int> v2(a1,a1 + SIZE);//copy of a1,通过数组地址初始化vector
vector <int> v3(a2,a2 + SIZE);//copy of a2,通过数组地址初始化vector
ostream_iterator<int> output(cout," ");
cout << "Vector V1 contains: ";
copy(v1.begin(),v1.end(),output);
//cout <<"V1.capacity() is:"<< v1.capacity() << endl;
cout << "\nVector V2 contains: ";
copy(v2.begin(), v2.end(), output);
cout << "\nVector V3 contains: ";
copy(v3.begin(), v3.end(), output);
//compare vectors v1 and v2 for equality
bool result = std::equal(v1.begin(),v1.end(),v2.begin());
cout << "\n\n Vector v1 " << (result ? "is" : "is not") << " equal to vector v2.\n";
//compare vectors v1 and v3 for equality
bool result2 = std::equal(v1.begin(), v1.end(), v3.begin());
cout << "\n\n Vector v1 " << (result2 ? "is" : "is not") << " equal to vector v3.\n";
//location represents pair of vector iterators
pair <vector<int>::iterator, vector<int>::iterator> location;
//check for mismatch between v1 and v3
location = std::mismatch(v1.begin(),v1.end(),v3.begin());
cout << "\nThere is a mismatch between v1 and v3 at location " << (location.first - v1.begin()) << "\nWhere v1 contains " << *location.first << " and v3 contains " << *location.second << "\n\n";
char c1[SIZE] = "HELLO";
char c2[SIZE] = "BYE BYE";
//perform lexicographical comparision of c1 and c2
bool result3 = lexicographical_compare(c1,c1+SIZE,c2,c2+SIZE);
cout << c1 << (result3 ? " is less than " : " is greater than or equal to ") << c2 << endl;
}//end of main
运行结果:
Vector V1 contains: 1 2 3 4 5 6 7 8 9 10
Vector V2 contains: 1 2 3 4 5 6 7 8 9 10
Vector V3 contains: 1 2 3 4 1000 6 7 8 9 10
Vector v1 is equal to vector v2.
Vector v1 is not equal to vector v3.
There is a mismatch between v1 and v3 at location 4
Where v1 contains 5 and v3 contains 1000
HELLO is greater than or equal to BYE BYE
这个程序就是比较初级,需要进一步研究的需要再仔细研究研究了。

被折叠的 条评论
为什么被折叠?



