Skip to content

Instantly share code, notes, and snippets.

@beyondwdq
Created June 20, 2015 07:45
Show Gist options
  • Save beyondwdq/521c5ee7cbe2ea6e35f3 to your computer and use it in GitHub Desktop.
Save beyondwdq/521c5ee7cbe2ea6e35f3 to your computer and use it in GitHub Desktop.
#include <map>
#include <vector>
#include <string>
#include <memory>
#include <iostream>
using namespace std;
template <typename T>
struct MyAllocator : public std::allocator<T>
{
//MyAllocator is a customized allocator. We may add some functions in the future.
};
struct Person
{
string name;
int age;
int height; //cm
float weight; //kg
};
class Roster
{
public:
bool add(const Person &p)
{
auto result = persons_.insert(std::make_pair(p.name, p));
return result.second;
}
void addBatch(const vector<Person> &persons)
{
for (auto &p : persons) {
this->add(p);
}
}
bool del(const string &name)
{
auto it = persons_.find(name);
if (it != persons_.end()) {
persons_.erase(it);
return true;
}
return false;
}
template <typename Pred>
int delIf(Pred pred)
{
int cnt = 0;
auto it = persons_.begin(),
ite = persons_.end();
while( it!=ite ) {
if (pred(it->second)) {
persons_.erase(it);
++cnt;
}
++it;
}
return cnt;
}
void show(ostream &os)
{
for (auto &kv : persons_){
os << kv.first << endl;
}
}
private:
std::map<string, Person> persons_;
};
int main(int argc, const char *argv[])
{
Person p1{"Gary", 40, 170, 65.5};
Person p2{"Linda", 30, 160, 55.2};
Person p3{"Jack", 35, 165, 60.5};
Person p4{"Lucy", 28, 170, 55.0};
vector<Person, MyAllocator<Person>> persons{p1, p2, p3};
Roster roster;
roster.addBatch(persons);
roster.show(cout);
roster.delIf([](const Person &p) { return p.age <=30; });
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment