c++11 boost - 算法 clamp、hex、unhex

clamp 是用来判断是否夹在一对值中间,如果在指定的一对值之间,返回本身的值,如果在左边,返回左值,在右边返回右值。

#include <iostream>
#include <vector>
using namespace std;

#include <boost/algorithm/clamp.hpp>
using namespace boost::algorithm;

void case1()
{
    assert(clamp(5, 1, 10) == 5);
    assert(clamp(5, 5, 10) == 5);
    assert(clamp(5, 1, 5) == 5);

    assert(clamp(5, 10, 15) == 10);
    assert(clamp(5, 0, 4) == 4);
}

//迭代,输出在3-9之间的值
void case2()
{
    vector<int> v = {2,4,6,8,10};

    clamp_range(v, ostream_iterator<int>(cout, ","), 3, 9);
}

int main()
{
    case1();
    case2();
}
[root@192 c++]# g++ -std=c++11 main.cpp
[root@192 c++]# ./a.out 
3,4,6,8,9,


hex 算法是用来执行十六进制的编码和解码。

// Copyright (c) 2015
// Author: Chrono Law
#include <iostream>
using namespace std;

#include <boost/algorithm/hex.hpp>
using namespace boost::algorithm;

void case1()
{
    string s;

	hex("a", ostream_iterator<char>(cout));
    cout << endl;  //十六进制的61既是10进制的97 

    hex("123", ostream_iterator<char>(cout));
    cout << endl;

    hex("ABC", std::back_inserter(s));  //编码后输出到字符串
    cout << s << endl;

    unhex(s, ostream_iterator<char>(cout));
    cout << endl;

    hex("+-*/", ostream_iterator<char>(cout));
    cout << endl;

    hex_lower("+-*/", ostream_iterator<char>(cout));
    cout << endl;
}

void case2()
try
{
    unhex("6162", ostream_iterator<char>(cout));
    //unhex("xyz", ostream_iterator<char>(cout));
    cout << endl;
}
catch(const boost::exception& e)
{
    cout << "unhex error" << endl;
}

int main()
{
    case1();
    case2();
}
[root@192 c++]# g++ -std=c++11 main.cpp
[root@192 c++]# ./a.out 
61
313233
414243
ABC
2B2D2A2F
2b2d2a2f
ab


上一篇: c++11 boost - 算法 foreach、minmax
下一篇: c++11 boost - 数学(1) constants、rational、ratio
作者邮箱: 203328517@qq.com