Jam*_*lis 44
有一种std::find()算法,它在迭代器范围内执行线性搜索,例如,
std::vector<int> v;
// Finds the first element in the vector that has the value 42:
// If there is no such value, it == v.end()
std::vector<int>::const_iterator it = std::find(v.begin(), v.end(), 42);
Run Code Online (Sandbox Code Playgroud)
如果对矢量进行了排序,则可以使用它std::binary_search()来测试向量中是否存在值,并将std::equal_range()迭代器开始和结束到向量中具有该值的元素范围.
R S*_*hko 21
究其原因是没有vector::find是因为没有算法的优势std::find(std::find是O(N)和一般的,你不能为载体做的更好).
但是你的原因map::find是因为它可以更有效(map::find是O(log N)这样,你总是想,超过使用std::find的地图).
谁告诉你的?vector在C++中有"查找"算法.讽刺地巧合的是,它被称为std::find.或者也许吧std::binary_search.或其他东西,取决于矢量中存储的数据的属性.
只有当算法的有效实现以某种方式与容器的内部细节相关联时,容器才能获得自己特定版本的通用算法(实现为容器方法).std::list<>::sort就是一个例子.
在所有其他情况下,算法由独立功能实现.