vector常见用法
1 #include <boost/foreach.hpp> 2 #include <iostream> 3 #include <vector> 4 #include <boost/foreach.hpp> 5 using namespace std; 6 using namespace boost; 7 class Test 8 { 9 public: 10 Test(int a){ 11 age=a; 12 } 13 int age; 14 bool operator < ( const Test& rhs ) const { //升序排序时必须写的函数 15 return age < rhs.age; 16 } 17 bool operator > ( const Test& rhs ) const { //降序排序时必须写的函数 18 return age > rhs.age; 19 } 20 }; 21 int main(void) 22 { 23 vector<Test> data; 24 Test t1(1); 25 Test t2(2); 26 Test t3(3); 27 Test t4(4); 28 data.push_back(t1); 29 data.push_back(t2); 30 data.push_back(t3); 31 data.push_back(t4); 32 //1. 遍历 33 for (vector<Test>::iterator it=data.begin(); it!=data.end(); it++) { 34 cout<<it->age<< std::endl; 35 } 36 //2. 排序 37 std::sort ( data.begin(), data.end(),greater<Test>() ); //lesss 升序 38 //3. boost遍历 39 BOOST_FOREACH(const Test& t,data) 40 { 41 cout<<t.age<< std::endl; 42 } 43 //4. 删除多个元素 44 for ( vector<Test>::iterator it = data.begin(); it != data.end(); ) { 45 if ( it->age == 1 || it->age == 3 ) { 46 it = data.erase ( it ); 47 } else { 48 it++; 49 } 50 } 51 std::sort ( data.begin(), data.end(),less<Test>() ); //lesss 升序 52 BOOST_FOREACH(const Test& t,data) 53 { 54 cout<<t.age<< std::endl; 55 } 57 return 0; 58 }