在向量中寻找项目

时间:2015-10-31 14:53:06

标签: c++ sorting c++11 search binary-search

我有一个实际值的向量,按递增顺序排序。

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

我可以通过迭代整个数组来解决这个问题:

vector<double> values;
double x;

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

有更快的方法来获得相同的结果吗?我在想二元搜索,但是如何实现呢?

4 个答案:

答案 0 :(得分:2)

使用std::lower_bound

#include <iterator>
#include <algorithm>

std::distance(begin(values)
            , std::lower_bound(begin(values), end(values), x));

如果该项目不存在,它将为您提供一个大于最后一个元素的索引。

DEMO

答案 1 :(得分:1)

函数lower_bound可能符合您的要求,您可以像下面这样使用它:

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

答案 2 :(得分:0)

您知道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;
}

正如彼得说的那样,这不会给你索引,而是一个是/否答案。但是,应该是最简单的方法,因此最快。

答案 3 :(得分:0)

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

相关问题