我可以做些什么来改进指针向量中的搜索?

What can I do to improve this search in a vector of pointers?

我的目标是检查 Person* 的向量中是否存在名为 person_namePerson 对象。该向量按名称的字母顺序排序。制作一个临时 Person 是我见过的使此 lower_bound 调用与名称一起使用的唯一方法。是否有更有效的方法来执行此操作,或者是否需要 temp 来执行比较?

//person_name is a string
Person temp(person_name);
auto it = lower_bound(personVec.begin(), personVec.end(), &temp, personCompare());
if (it != personVec.end() && (*it)->getName() == person_name) {}
else { return false;  }

不需要temp。您需要具有正确签名的比较器。

例如,取消引用 personVec.begin() 结果时 Person*& 并且 person_namePersonName 类型那么你可以有这样签名的比较器:

bool compare(Person* const& a, PersonName const& b);

这只是普通函数,但具有此类签名的其他可调用对象也可以使用。然后你可以直接使用lower_boundperson_name

auto it = lower_bound(personVec.begin(), personVec.end(), person_name, compare);

您的一般问题是关于如何提高性能。这是不可能通过看到 4 行程序来暗示的。应该通过在重数据负载下分析整个程序并分析结果来找出它。例如,personVec 的排序可能比其中的 lower_bound 花费更多的时间。然后使用 unordered_set 而不是 vector 可以比优化 vector 中的搜索功能得到更好的结果。