浏览 3505 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2008-07-29
boost::array
#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; }
运行结果:
#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 }
运行结果: 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |