1 #include <iostream> 2 #include <string> 3 #include <boost/array.hpp> 4 //异构的容器 5 #include <boost/any.hpp> 6 #include <vector> 7 #include <typeinfo> 8 #include <algorithm> 9 using namespace std; 10 using namespace boost; 11 12 void main() 13 { 14 boost::array<string, 5>mystr = { "12","ab","34","ef","334" }; 15 boost::array<string, 5>::iterator ib = mystr.begin(); 16 boost::array<string, 5>::iterator ie = mystr.end(); 17 for (; ib != ie; ib++) 18 { 19 cout << *ib << endl; 20 } 21 22 //返回数组首地址 23 string *p = mystr.data(); 24 cout << *p << endl; 25 mystr[3] = "90"; 26 mystr.at(3) = "123"; 27 28 //异构容器 29 std::vector<boost::any> s_values; 30 s_values.push_back(123); 31 s_values.push_back('A'); 32 s_values.push_back(19.8); 33 s_values.push_back("12345"); 34 //cout << boost::any_cast<double>(s_values[2]) << endl; 35 36 for_each(s_values.begin(),s_values.end(), 37 [](const boost::any &anydata) 38 { 39 //获取类型 40 const std::type_info &ti = anydata.type(); 41 //根据类型执行相应的操作 42 if (ti == typeid(int)) 43 { 44 cout << boost::any_cast<int>(anydata) << endl; 45 } 46 else if (ti == typeid(double)) 47 { 48 cout << boost::any_cast<double>(anydata) << endl; 49 } 50 else if (ti == typeid(const char *)) 51 { 52 cout << boost::any_cast<const char *>(anydata) << endl; 53 } 54 else if (ti == typeid(char)) 55 { 56 cout << boost::any_cast<char>(anydata) << endl; 57 } 58 }); 59 60 cin.get(); 61 }