结构体数组,按字段查找
我有一个按字段 name 排好序的结构体数组,怎样使用 stl 来查找?
struct User { std::string name; std::string address; //more fields... }; //.... std::vector<User> v; // expected searching code auto i = std::lower_bound(v.begin(), v.end(), "whinah", CompareName());
怎样定义 CompareName ?
struct CompareName { bool operator()(const User& x, const std::string& y) const { return x.name < y; } bool operator()(const std::string& x, const User& y) const { return x < y.name; } };
一般的 Compare 这样定义:
struct CompareName { bool operator()(const User& x, const User& y) const { return x.name < y.name; } };
这样的 Compare 只能用于排序,如果要用于查找,我们必须先构造一个 User 对象,再把想查找的name assign 这个 User::name, ....
posted on 2011-06-13 11:38 能发波 阅读(113) 评论(0) 编辑 收藏 举报