对于这个答案,我假设你已经做了使用的明智决定std::vector超过其他可用容器 https://stackoverflow.com/questions/471432/in-which-scenario-do-i-use-a-particular-stl-container/471461#471461.
我真的需要执行 for 循环来循环所有元素吗?
不,您不必滚动for
-循环查找元素。在容器中查找元素的惯用方法是使用标准库中的算法。不管你should自己动手确实取决于具体情况。
为了帮助您决定...
替代方案 1:
std::find() http://en.cppreference.com/w/cpp/algorithm/find要求有一个适合您的相等比较器node
数据类型,可能像这样简单:
bool operator ==(node const& l, node const& r)
{
return l.data == r.data;
}
然后,给定一个required
node
,您可以搜索该元素。这会返回一个iterator (or a pointer如果您使用的是普通的旧数组)。如果您需要index,这需要一点计算:
auto i = std::find(v.begin(), v.end(), required);
if (i != v.end())
{
std::cout << i->data << " found at index " << i - v.begin() << std::endl;
}
else
{
std::cout << "Item not found" << std::endl;
}
替代方案 2:
如果创建一个node
太昂贵或者你没有相等运算符,更好的方法是使用std::find_if() http://en.cppreference.com/w/cpp/algorithm/find,它需要一个谓词(这里我使用 lambda 因为它很简洁,但你可以使用像这个答案一样的函子 https://stackoverflow.com/a/14919397/78845):
// Alternative linear search, using a predicate...
auto i = std::find_if(v.begin(), v.end(), [](node const& n){return n.data == 444;});
if (i != v.end())
{
std::cout << i->data << " found at index " << i - v.begin() << std::endl;
}
else
{
std::cout << "Item not found" << std::endl;
}
或者有更快的方法吗?
同样,这取决于情况。std::find()
and std::find_if()
以线性时间运行(O(n)),和你的一样for
-loop.
也就是说,使用std::find()
or std::find_if()
不会涉及随机访问或对容器进行索引(它们使用迭代器),但与您的相比,它们可能需要一些额外的代码for-
loop.
替代方案 3:
如果运行时间很关键并且您的数组已排序(比如std::sort() http://en.cppreference.com/w/cpp/algorithm/sort),您可以执行二分搜索,该搜索以对数时间运行(O(log n)). std::lower_bound() http://en.cppreference.com/w/cpp/algorithm/lower_bound实现对第一个元素的二分搜索不小于给定值。不幸的是,它不需要谓词,但需要一个适合您的小于比较器node
数据类型,例如:
bool operator <(node const& l, node const& r)
{
return l.data < r.data;
}
调用类似于std::find()
并返回一个iterator,但需要额外检查:
auto i = std::lower_bound(v.begin(), v.end(), required);
if (i != v.end() && i->data == required.data)
{
std::cout << i->data << " found at index " << i - v.begin() << std::endl;
}
else
{
std::cout << "Item not found" << std::endl;
}
这些函数来自算法库 http://en.cppreference.com/w/cpp/algorithm与任何提供迭代器的容器一起使用,因此切换到另一个容器std::vector
将快速且易于测试和维护。
决定权在你!
[请参阅此处的演示。] http://ideone.com/WLXXFg