stl有助于在c++中以更快的方式搜索大数组吗

does stl help to to search a big array in faster way in c++?

本文关键字:方式 搜索 数组 有助于 c++ stl      更新时间:2023-10-16

我有一个大矩阵,它可以大到10000x10000甚至更大。我将搜索一些值中元素的所有索引,这个过程将重复多次。c++代码看起来像

double data[5000][5000];
int search_number = 4000;
double search_main_value[4000];
vector<int> found_index[4000];
// fill search main value array here 
// search_main_value[0] = ...;
// ...
// search_main_value[3999] = ...;
for (int n=0; n<4000; n++)  // for each search main value
{
  for (int row=0; row<5000; row++)
  {
    for (int col=0; col<5000; col++)
    {
      double lb = search_main_value[n]-0.5;
      double ub = search_main_value[n]+0.5;
      if ( (data[row][col]>=lb) && (data[row][col]<ub) )
      {
        found_index[n].push_back(col*5000+row);
      } 
    }
  } 
}

但是,如果数组的大小太大,并且search_value_array很大,则此搜索非常缓慢。我试图使用std算法来提高搜索速度,但我阅读了帮助,似乎stl容器一次只搜索一个数字,而不是一个范围。

==============================================

我遵循网上给出的例子,比如

bool compare(const double& num, const double&d) {return ( (num>=d-0.5) && (num<d+0.5))}
double *start = data;
double *end = data+5000*5000;
for (int n=0; n<4000; n++)
{
  auto found = find_if(start, end, std::bind(compare, std::placeholders::_1, search_main_value[n]);
}

但这并没有编译,它说std没有绑定。此外,它似乎返回的是找到的值,而不是索引。如何将查找到的保存为std::矢量?我尝试

std::vector<double> found_vec;
found_vec.assign(found);

但它不会编译。

==============================================

我还尝试先对数据进行排序,然后用binary_search 搜索数据

struct MyComparator
{
  bool operator()(const pair<double, int> &d1, const pair<double, int> &d2) const {return d1.first<d2.first;}
  bool operator(double x)(const pair<double, int> &d) const {return (d.first>=x+0.5) && (d.first<0.5);}
};
std::vector< std::pair<double, int> > sortData;
// fill sortData here with value, index pair
std::sort(sortData.begin(), sortData.end(), MyComparator()); // it works
...
std::find_if(sortData.begin(), sortData.end(), MyComparator(search_main_value[n]));

但最后一段代码没有编译

由于这个过程将重复多次,我建议您对元素进行排序,并将其与索引一起存储在向量中,作为一对。在给定这个向量的情况下,你可以很容易地找到一个或多个基本索引。

      vector<pair<int, int> > sortedElementsWithIndex;

对包含原始数组中的元素和索引。您可以根据元素值对这个向量进行排序。