类型自动推导:
#include <iostream> #include <boost/typeof/typeof.hpp> #include <vector> #include <string> using namespace std; vector<string> func() { vector<string> v(10); return v; } int main() { BOOST_TYPEOF(2.1*3) x = 2.1*3; BOOST_AUTO(y,2.1*3); //我感觉 BOOST_AUTO 更好用些。第一个参数是左值,第二个>参数是右值。 BOOST_AUTO(vect,func()); cout<<x<<"\n"<<y<<"\n"<<vect.size()<<endl; //不过用了自动推导之后,TAGS智能提示就不能用了,可以理解。 }
快速向容器中增加数据:
#include <iostream> #include <boost/assign.hpp> #include <vector> using namespace std; using namespace boost::assign; //必须要使用 using 指示符,只有这样才能让重载的 += 操作符在作用域内生效 int main() { vector<int> vect1,vect2; vect1 += 1,2,3,4,5,10*2; cout<<"vect1's size is: "<<vect1.size()<<endl; for(int i = 0; i < vect1.size();i++) { cout<<vect1[i]<<endl; }
push_back(vect2)(5)(15)(25)(35); //push_back(vect2),5,15,25,35; cout<<"vect2's size is: "<<vect2.size()<<endl; for(int i = 0; i < vect2.size();i++) { cout<<vect2[i]<<endl; } vector<int> vect3 = list_of(100)(200)(300)(400); cout<<"vect3's size is: "<<vect3.size()<<endl; for(int i = 0;i < vect3.size();i++) { cout<<vect3[i]<<endl; } }
交换元素或数组:
#include <iostream> #include <boost/swap.hpp> int main() { int a1[3] = {1,2,3}; int a2[3] = {4,5,6}; boost::swap(a1,a2); for(int i=0;i<3;i++) { std::cout<<a1[i]<<std::endl; } }