论坛首页 编程语言技术论坛

boost笔记3(boost::array)

浏览 3503 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-07-29  
C++

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

论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics