#include <iostream> #include <vector> #include <algorithm> #include <memory> using namespace std; class Display { public: Display(int pid):removeBoo(false) { id = pid; } ~Display() { } void showInfo(){ cout << "dispatch evt id: "<< id << endl; } // bool removeBoo; // int getId(){ return id; } private: int id; }; std::vector<std::shared_ptr<Display>> s_display_vec; // 不需要保持原有顺序的 void removeEleTest1() { std::vector <std::shared_ptr<Display>>::iterator iter = s_display_vec.begin(); for (; iter != s_display_vec.end();) { if ((*iter)->removeBoo) { std::swap(*iter,s_display_vec.back()); s_display_vec.pop_back();
// c++11这样做没必要 //if(s_display_vec.size() < 1) break;
} else { (*iter)->showInfo(); ++iter; } } } ///* // 需要保持原有顺序的 void removeEleTest2() { std::vector <std::shared_ptr<Display>>::iterator iter = s_display_vec.begin(); for (; iter != s_display_vec.end();) { if ((*iter)->removeBoo) { // 在这里将target的标记,记录为未加入列表 //(*iter) if (iter == s_display_vec.end()) { cout << "--a delete " <<(*iter)->getId()<<"--"<< endl; s_display_vec.pop_back(); break; } else { cout << "--b delete " <<(*iter)->getId()<<"--"<< endl; iter = s_display_vec.erase(iter); } } else { (*iter)->showInfo(); ++iter; } } } //*/ int main() { cout << "Hello world!" << endl; //int j = 0; std::shared_ptr<Display> dp_0 = std::make_shared<Display>(0); std::shared_ptr<Display> dp_1 = std::make_shared<Display>(1); std::shared_ptr<Display> dp_2 = std::make_shared<Display>(2); std::shared_ptr<Display> dp_3 = std::make_shared<Display>(3); std::shared_ptr<Display> dp_4 = std::make_shared<Display>(4); ///* s_display_vec.push_back(dp_0); s_display_vec.push_back(dp_1); s_display_vec.push_back(dp_2); s_display_vec.push_back(dp_3); s_display_vec.push_back(dp_4); cout << "s_display_vec.size: "<< s_display_vec.size() << endl; cout << "------------------" << endl; // 设置哪一个可以被删除 dp_3->removeBoo = true; removeEleTest2(); cout << "----------aaa--------" << endl; removeEleTest2(); cout << "s_display_vec.size: "<< s_display_vec.size() << endl; //*/ return 0; }