栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

四、C++语言进阶:Boost入门

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

四、C++语言进阶:Boost入门

4 Boost入门 4.1 简介

Boost库是一个可移植、提供源代码的C++库,作为标准库的后备,是C++标准化进程的开发引擎之一,是为C++语言标准库提供扩展的一些C++程序库的总称。

4.2 使用 4.2.1 lamdba表达式

lambda库通过创建一个匿名的lambda表达式来代替实名的函数对象

  • HelloWorld.cpp
#include   
#include  
using namespace boost::lambda; 
using namespace std; 
int main() {
    (cout << _1 << " " << _2)("Hello","World");
}

结果:

[root@localhost 4]# ./a.out 
Hello World[root@localhost 4]# 
  • HelloWorld2.cpp
#include   
#include  
using namespace boost::lambda; 
using namespace std;

int main(){  
    auto func = std::cout << _1 << " " << _2;
    func("Hello","World");
}
  • for_each.cpp
#include   
#include   
#include   
#include   
#include   
int main()  
{  
    using namespace boost::lambda;  
    using namespace std;  
    int arr[] = {1,2,3,4,5,6};
    for_each(arr,arr+6, cout << _1 << " " );
    cout << endl;

    vector vec(arr,arr+6);
    for_each(vec.begin(),vec.end(), cout << _1 << " " );
    cout << endl;
}

结果:

[root@localhost 4]# ./a.out 
1 2 3 4 5 6 
1 2 3 4 5 6

注:如果需要使用_1、_2的成员变量。需要使用绑定bind()。

#include   
#include   
#include   
#include   
#include "boost/lambda/lambda.hpp"  
#include "boost/lambda/bind.hpp"  

using namespace boost::lambda; 
using namespace std; 
int main() {  
    map kv;
    kv[110] = "匪警";
    kv[119] = "火警";
    kv[120] = "急救中心";
    for_each(kv.begin(),kv.end(), cout << bind(&map::value_type::first,_1) << 't' <<  bind(&map::value_type::second,_1) << 'n'); 
}

结果:

[root@localhost 4]# ./a.out 
110	匪警
119	火警
120	急救中心
4.2.2 容器中存放任意类型值
#include 
#include 
#include 
#include 
#include 

int main(){
    using namespace std;
    using namespace boost;

    any a1 = 10;
    any a2 = 1.1f;
    any a3 = string("abc");
    any a4 = "abcefg";

    cout << any_cast(a1) << endl;
    cout << any_cast(a2) << endl;
    cout << any_cast(a3) << endl;
    cout << any_cast(a4) << endl;

    vector vec2 = {"abcd",123,3.14};
    cout << any_cast(vec2[0]) << endl;
    cout << any_cast(vec2[1]) << endl;
    cout << any_cast(vec2[2]) << endl;

    vector vec;
    vec.push_back(10);
    vec.push_back(12.4);
    vec.push_back(string("string"));
    char const* c_str = "const char*";
    vec.push_back(c_str);

    cout << any_cast(vec[0]) << endl
            << any_cast(vec[1]) << endl
            << any_cast(vec[2]) << endl
            << any_cast(vec[3]) << endl;

    // copy(vec.begin(),vec.end(),ostream_iterator(cout,","));
}

结果:

10
1.1
abc
abcefg
abcd
123
3.14
10
12.4
string
const char*

注:
any_cast<>中的类型不是原来的类型会抛出异常。
any已经成为C++17的标准库组件。

4.2.3 数据转化
  • 字符串转数字
#include 
#include 
int main(){
    int i = boost::lexical_cast("100");
    float f = boost::lexical_cast("2.01");
    char chars[] = "1234";
    int n = boost::lexical_cast(chars,strlen(chars));
    std::cout << i << " " << f << " " << n << std::endl;
    
    // f = boost::lexical_cast("2.01"); // 类型不匹配抛异常
}

结果:

[root@localhost 4]# ./a.out 
100 2.01 1234

注:C++11可以使用stoi()、stof()等

  • 数字转字符串
#include 
#include 
#include 
int main(){
    std::string str1 = boost::lexical_cast(100);
    std::string str2 = boost::lexical_cast(2.01);
    std::cout << str1 << " " << str2 << std::endl;
}

结果:

[root@localhost 4]# ./a.out 
100 2.0099999999999998
  • 多态对象转换
#include 
#include 
using namespace std;
class Base{
public:
    void Func(){
        cout << "Base" << endl;
    }
    virtual ~Base(){}
};
class Derive : public Base{
public:
    void Func(){
        cout << "Derive" << endl;
    }
};
int main(){
    Base* b = new Derive;
    boost::polymorphic_cast(b)->Func();
}

结果:

[root@localhost 4]# ./a.out 
Derive
4.2.4指针容器

特点:容器销毁自动释放指针

类型说明
ptr_vector指针向量
ptr_set指针集合
ptr_array指针数组
ptr_multimap指针一对多映射
#include 
#include 
#include 
using namespace std;
int main(){
    boost::ptr_vector pvec;
    for(int i=0;i<10;++i){
        pvec.push_back(new int(i));
    }
    for(auto n:pvec){
        cout << n << " ";
    }
    cout << endl;

    boost::ptr_set s;
    for(size_t i=0;i<10;i++){
        s.insert(new int(i));
    }
    for(auto n:s){
        cout << n << " ";
    }
    cout << endl;
}

结果:

[root@localhost 4]# ./a.out 
0 1 2 3 4 5 6 7 8 9 
0 1 2 3 4 5 6 7 8 9 
4.2.5 退出处理

变量离开(正常/异常)作用域,触发处理代码。

#include 
#include 
using namespace std;
int main(){
    {
        int *a = new int(10);
        BOOST_SCOPE_EXIT(a){
            delete a;
        }BOOST_SCOPE_EXIT_END

        cout << *a << endl;
    }
}

结果:

[root@localhost 4]# ./a.out 
10

注:不止用在new/delete,也用在fopen()/fclose(),dlopen()/dlclose()等。与析构函数相似的作用。

4.2.6 遍历BOOST_FOREACH
#include 
#include 
using namespace std;
int main(){
    int arr[] = {1,2,3,4,5};
    BOOST_FOREACH(int a,arr) cout << a << endl;
}

结果:

[root@localhost 4]# ./a.out 
1
2
3
4
5
4.2.7 函数绑定

全局函数:boost::bind(函数名, 参数1,参数2,...)
成员函数:boost::bind(&类名::方法名,类实例指针,参数1,参数2)

#include 
#include 
#include 
using namespace std;
bool comp(int a,int b){
    return a
    int arr[] = {1,2,3,4,5};
    cout << count_if(arr,arr+5,boost::bind(comp,_1,3)) << endl;
    cout << count_if(arr,arr+5,boost::bind(comp,2,_1)) << endl;
}

结果:

[root@localhost 4]# ./a.out 
2
3

注:bind支持最多九个参数。占位符被命名为 _1,_2, _3, _4, 直至 _9。

4.2.8 不可复制类
#include 

class Test:private boost::nocopyable{
    // ...  
};

C++11禁用拷贝构造函数的两种方法:

  • (1)设置成delete
#include 
using namespace std;
class Test {
public:
    Test(){}
    Test(const Test&) = delete;
    Test& operator=(const Test&) = delete;
};
int main() {
    Test t;
    Test t2 = t;
    t2 = t;
}

报错:

[root@localhost 4]# g++ Test.cpp
Test.cpp: In function ‘int main()’:
Test.cpp:11:15: error: use of deleted function ‘Test::Test(const Test&)’
     Test t2 = t;
               ^
Test.cpp:6:5: note: declared here
     Test(const Test&) = delete;
     ^~~~
Test.cpp:12:10: error: use of deleted function ‘Test& Test::operator=(const Test&)’
     t2 = t;
          ^
Test.cpp:7:11: note: declared here
     Test& operator=(const Test&) = delete;
           ^~~~~~~~
  • (2)设置成private:
#include 
using namespace std;
class Test {
public:
    Test(){}
private:
    Test(const Test&) {}
    Test& operator=(const Test&) {
        return *this;
    };
};
int main() {
    Test t;
    Test t2 = t;
    t2 = t;
}

报错:

[root@localhost 4]# g++ Test.cpp
Test.cpp: In function ‘int main()’:
Test.cpp:14:15: error: ‘Test::Test(const Test&)’ is private within this context
     Test t2 = t;
               ^
Test.cpp:7:5: note: declared private here
     Test(const Test&) {}
     ^~~~
Test.cpp:15:10: error: ‘Test& Test::operator=(const Test&)’ is private within this context
     t2 = t;
          ^
Test.cpp:8:11: note: declared private here
     Test& operator=(const Test&) {
           ^~~~~~~~
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/968310.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号