假设我有一个名为Bank的类,其属性为
class Bank {
string _name;
}
现在我宣布一个Bank的矢量。
vector<Bank> list;
给定一个字符串,如何在矢量列表中搜索具有相同字符串名称的特定Bank对象?
我正在尝试避免执行循环并查看是否存在可以执行此操作的stl函数。
答案 0 :(得分:13)
您可以使用良好的旧线性搜索:
auto it = std::find_if(list.begin(), list.end(), [&](const Bank& bank)
{
return bank._name == the_name_you_are_looking_for;
});
如果列表中没有这样的bank,则返回结束迭代器:
if (it == list.end())
{
// no bank in the list with the name you were looking for :-(
}
else
{
// *it is the first bank in the list with the name you were looking for :-)
}
如果你的编译器来自石器时代,它就不会理解lambdas和auto
。未经测试的C ++ 98代码:
struct NameFinder
{
const std::string& captured_name;
bool operator()(const Bank& bank) const
{
return bank.name == captured_name;
}
};
NameFinder finder = {the_name_you_are_looking_for};
std::vector<Bank>::iterator it = std::find_if(list.begin(), list.end(), finder);
答案 1 :(得分:2)
根据受欢迎的要求,只是附注,以警告将来被这个问题吸引的潜在初学者:
std::find
正在使用线性方法,因为底层对象(在这种情况下为向量)的设计并未考虑搜索效率。
考虑到普通PC中可用的计算能力,使用矢量搜索时间至关重要的数据可能会有效,但如果要处理的数据量增加,可能会很快变慢。
如果您需要快速搜索,您可以使用其他容器(std::set
,std::map
和一些变体),以便在对数时间内进行检索。
您甚至可以在unordered_set
和unordered_map
等容器中使用哈希表进行(近乎)即时访问,但其他操作的成本也相应增加。这都是平衡问题。
您还可以先对矢量进行排序,然后使用std :: algorithms执行二分法搜索,例如binary_search
,如果您有严格的订单或lower_bound
,upper_bound
和{{1如果你只能在你的元素上定义一个部分顺序。
答案 2 :(得分:0)
std::find将允许您以各种方式搜索向量。