Created
April 25, 2019 17:38
-
-
Save slwu89/38ccea38434d940e9211af15448f2723 to your computer and use it in GitHub Desktop.
store humans in linked-list and some attributes of them outside, delete multiple at once
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.cpp | |
// test_humans | |
// | |
// Created by Sean Wu on 5/31/18. | |
// Copyright © 2018 Sean Wu. All rights reserved. | |
// | |
#include <iostream> | |
#include <string> | |
#include <vector> | |
#include <list> | |
#include <memory> | |
#include <math.h> | |
class person { | |
public: | |
person(const std::string& name_, const bool alive_) : name(name_), alive(alive_) { | |
std::cout << name << " being born at " << this << std::endl; | |
}; | |
~person(){ | |
std::cout << name << " being killed at " << this << std::endl; | |
}; | |
/* move operators */ | |
person(person&&) = default; | |
person& operator=(person&&) = default; | |
/* copy operators */ | |
person(person&) = delete; | |
person& operator=(person&) = delete; | |
std::string get_name(){ | |
return name; | |
}; | |
bool alive; | |
private: | |
std::string name; | |
}; | |
int main(int argc, const char * argv[]) { | |
std::list<std::unique_ptr<person> > vec1; | |
std::vector<int > vec2; | |
vec1.emplace_back(std::make_unique<person>("alice",false)); | |
vec2.emplace_back(1); | |
vec1.emplace_back(std::make_unique<person>("bob",true)); | |
vec2.emplace_back(2); | |
vec1.emplace_back(std::make_unique<person>("john",false)); | |
vec2.emplace_back(3); | |
vec1.emplace_back(std::make_unique<person>("shirley",true)); | |
vec2.emplace_back(4); | |
vec1.emplace_back(std::make_unique<person>("charley",false)); | |
vec2.emplace_back(5); | |
std::cout << " --- erasing --- " << std::endl; | |
size_t i = 0; | |
for(auto it=vec1.begin(); it != vec1.end(); ++it){ | |
if(!it->get()->alive){ | |
vec1.erase(it); | |
vec2.erase(vec2.begin() + i); | |
} else { | |
i++; | |
} | |
} | |
std::cout << " --- done --- " << std::endl; | |
i = 0; | |
for(auto it=vec1.begin(); it != vec1.end(); ++it){ | |
std::cout << "name : " << it->get()->get_name() << " alive : " << it->get()->alive; | |
std::cout << " val : " << vec2[i] << " -- \n"; | |
i++; | |
} | |
std::cout << " --- exiting program --- " << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment