STL源码剖析学习之基本算法

来源:互联网 发布:java前端 编辑:程序博客网 时间:2024/05/17 01:21
//STL之基本算法
//学习目的:学习基本算法的使用
/*

//本程序代码来源《STL源码剖析》
*/

//file:6algobase.cpp
#include <algorithm>
#include <vector>
#include <functional>
#include <iostream>
#include <iterator> 
#include <string>
using namespace std;

template<class T>
struct display
{
void operator() (const T& x) const
{
cout << x << ' ';
}
};

int main()
{
int ia[9] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
vector<int> iv1(ia, ia + 5);
vector<int> iv2(ia, ia + 9);

//{0, 1, 2, 3, 4}v.s{0, 1, 2, 3, 4, 5, 6, 7, 8}
cout << *(mismatch(iv1.begin(), iv1.end(), iv2.begin()).first) << endl;//?无效值-33686019
cout << *(mismatch(iv1.begin(), iv1.end(), iv2.begin()).second) << endl; //5
//以上判断两个区间的第一个不匹配点,返回一个由两个迭代器组成的pair,其中第一个迭代器指向
//第一区间的不匹配点,第二个迭代器指向第二区间的不匹配点
//上述写法很危险,应该先判断迭代器是否不等于容器的end(),然后才可以做输出操作


//如果两个序列在[first,last)区间内相等,equal()返回true
//如果第二序列的元素比较多,多出来的元素不予考虑
cout << equal(iv1.begin(), iv1.end(), iv2.begin()) << endl; //1, true

cout << equal(iv1.begin(), iv1.end(), &ia[3]) << endl;  //0, false
//{0, 1, 2, 3, 4}不等于{3, 4, 5, 6, 7}

cout << equal(iv1.begin(), iv1.end(), &ia[3], less<int>()) << endl; //1
//{0, 1, 2, 3, 4}小于{3, 4, 5, 6, 7}

fill(iv1.begin(), iv1.end(), 9);  //区间内全部填9
for_each(iv1.begin(), iv1.end(), display<int>()); //9 9 9 9 9

fill_n(iv1.begin(), 3, 7); //从迭代器所指位置开始,填3个7

vector<int>::iterator ite1 = iv1.begin();//指向7
vector<int>::iterator ite2 = ite1;//指向7
advance(ite2, 3);//指向9

iter_swap(ite1, ite2);  //将两个迭代器所指元素对调
cout << *ite1 << ' ' << *ite2 << endl;   //9 7
for_each(iv1.begin(), iv1.end(), display<int>()); //9 7 7 7 9

//以下取两值之大者
cout << _cpp_max(*ite1, *ite2) << endl;  //Visual C++ 无法使用max和min,
//因为没有定义这些函数模板。原因是名字min和max与<windows.h>中传统的min/max宏定义有冲突

//准备两个字符串数组
string stra1[] = {"Jamie", "JJHou", "Jason"};
string stra2[] = {"Jamie", "JJhou", "Jerry"};

cout << lexicographical_compare(stra1, stra1+2, stra2, stra2+2) << endl;
//1 (stra1 < stra2)
cout << lexicographical_compare(stra1, stra1+2, stra2, stra2+2, greater<string>()) << endl;
//0 (stra1 不大于 stra2)

getchar();
}