Define operator< for your structure to provide an ordering relation between Customer instances:
struct Customer {
...
friend bool operator<(const Customer& a, const Customer& b) {
return a.id < b.id;
}
};
Use this cheatsheet (in particular the flowchart at the bottom) to decide which container you should use in your particular program. If it’s std::set, your sorting is done whenever you insert a Customer into the set. If it’s std::list, call the sort() member function on the list:
std::list<Customer> customers;
customers.push_back(Customer(...));
...
customers.sort();
If it’s std::vector or std::deque, use std::sort() from the <algorithm> header:
std::vector<Customer> customers;
customers.push_back(Customer(...));
...
std::sort(customers.begin(), customers.end());
If you need to sort in multiple ways, define a sorting function for each ordering:
struct Customer {
...
static bool sort_by_name(const Customer& a, const Customer& b) {
return a.name < b.name;
}
};
Then tell std::list::sort() or std::sort() to use that comparator:
customers.sort(Customer::sort_by_name);
std::sort(customers.begin(), customers.end(), Customer::sort_by_name);
std::set<Customer*,CompareFunctor>, remove and re-insert whenever you update a Customer) and traverse this in linear time.