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

时间:2013-07-25 05:05:37

标签: c++ templates search

我有一个大矩阵可能大到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 :: vector?我试试

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]));

但最后一段代码无法编译

1 个答案:

答案 0 :(得分:4)

由于此过程将重复多次,我建议您对元素进行排序,并将其与索引一起存储在一个向量中。并且您可以在给定此向量的情况下轻松找到基本索引。

      vector<pair<int, int> > sortedElementsWithIndex;

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

相关问题