在矢量中查找项目

Seek item within vector

本文关键字:查找 项目      更新时间:2023-10-16

我有一个实数向量,按升序排序。

这些值可以在[0, 1]的范围内。然后我在这个范围内选择一个值x,我需要找到哪个是大于或等于x的较小值的索引。

我可以通过在整个阵列上迭代来解决这个问题:

vector<double> values;
double x;
for (auto val : values)
{
    if (x <= values)
    {
        // found
        break;
    }
}

有没有更快的方法可以得到同样的结果?我在考虑二进制搜索,但是如何实现呢?

使用std::lower_bound:

#include <iterator>
#include <algorithm>
std::distance(begin(values)
            , std::lower_bound(begin(values), end(values), x));

如果该项不存在,它将为您提供一个比上一个元素大一的索引。

DEMO

函数lower_bound可能会满足您的需求,您可以像下面这样使用它:

iter =lower_bound(values.begin(),values.end(),x);

您可以像数组一样使用运算符[]直接访问向量中的项,而不是使用迭代器从头开始。我想你已经知道二进制搜索了。在数组中实现它是你可以在任何地方找到的东西,所以我不会在这里向你解释。只需将向量视为数组即可。

你知道SO不是一个你要求别人给你写代码的网站,所以以std::binary_search为例,让你的方式:

// binary_search example
#include <iostream>     // std::cout
#include <algorithm>    // std::binary_search, std::sort
#include <vector>       // std::vector
bool myfunction (int i,int j) { return (i<j); }
int main () {
  int myints[] = {1,2,3,4,5,4,3,2,1};
  std::vector<int> v(myints,myints+9);                         // 1 2 3 4 5 4 3 2 1
  // using default comparison:
  std::sort (v.begin(), v.end());
  std::cout << "looking for a 3... ";
  if (std::binary_search (v.begin(), v.end(), 3))
    std::cout << "found!n"; else std::cout << "not found.n";
  // using myfunction as comp:
  std::sort (v.begin(), v.end(), myfunction);
  std::cout << "looking for a 6... ";
  if (std::binary_search (v.begin(), v.end(), 6, myfunction))
    std::cout << "found!n"; else std::cout << "not found.n";
  return 0;
}

正如Piotr所说,这不会给你指数,而是一个是/否的答案。然而,这应该是最简单的方法,因此也是最快的方法。