boost笔记3(boost::array)

本文介绍Boost::array作为数组容器的实现,探讨其相对于STL容器的优势,并通过两个示例程序展示如何使用Boost::array进行数组操作,包括初始化、修改元素、排序及应用STL算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

boost::array
很遗憾,STL标准容器中并没有数组容器, 对于一组固定大小的数据, 用vector并不一定比Array合适,vector毕竟是大小可变的。而且个人认为,这样会使概念不够清晰,毕竟Array和vector概念上并不是完全等同的。
boost::array就是数组的容器类实现,他完全兼容STL,很有希望被加入下一代的C++标准中。Boost::array内部仍然是固定长度,但是却拥有STL容器兼容的接口,这样就使的Boost::array能够支持STL中的算法,能够和STL中的许多组建协同工作。


例子程序1:

#include <iostream>
#include <algorithm>
#include <functional>
#include <boost/array.hpp>

using namespace std;
using namespace boost;

template <class T>
inline void print_elements (const T& coll, const char* optcstr="")
{
    typename T::const_iterator pos;

    std::cout << optcstr;
    for (pos=coll.begin(); pos!=coll.end(); ++pos) {
        std::cout << *pos << ' ';
    }
    std::cout << std::endl;
}

int main()
{
    // create and initialize array
    array<int,10> a = { { 1, 2, 3, 4, 5 } };

    print_elements(a);

    // modify elements directly
    for (unsigned i=0; i<a.size(); ++i) {
        ++a[i];
    }
    print_elements(a);

    // change order using an STL algorithm
    reverse(a.begin(),a.end());
    print_elements(a);

    // negate elements using STL framework
    transform(a.begin(),a.end(),    // source
              a.begin(),            // destination
              negate<int>());       // operation
    print_elements(a);

    return 0;
}

 

运行结果:
1 2 3 4 5 0 0 0 0 0
2 3 4 5 6 1 1 1 1 1
1 1 1 1 1 6 5 4 3 2
-1 -1 -1 -1 -1 -6 -5 -4 -3 -2

 


例子程序2:

#include <string>
#include <iostream>
#include <boost/array.hpp>

template <class T>
void print_elements (const T& x)
{
    for (unsigned i=0; i<x.size(); ++i) {
        std::cout << " " << x[i];
    }
    std::cout << std::endl;
}
int main()
{
    // create array of four seasons
    boost::array<std::string,4> seasons = {
        { "spring", "summer", "autumn", "winter" }
    };

    // copy and change order
    boost::array<std::string,4> seasons_orig = seasons;
    for (unsigned i=seasons.size()-1; i>0; --i) {
        std::swap(seasons.at(i),seasons.at((i+1)%seasons.size()));
    }

    std::cout << "one way:   ";
    print_elements(seasons);

    // try swap()
    std::cout << "other way: ";
    std::swap(seasons,seasons_orig);
    print_elements(seasons);

    // try reverse iterators
    std::cout << "reverse:   ";
    for (boost::array<std::string,4>::reverse_iterator pos
           =seasons.rbegin(); pos<seasons.rend(); ++pos) {
        std::cout << " " << *pos;
    }
    std::cout << std::endl;

    return 0;  // makes Visual-C++ compiler happy
}

 

运行结果:
one way:    winter spring summer autumn
other way:  spring summer autumn winter
reverse:    winter autumn summer spring

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值