c++ - STL 是否有助于在 C++ 中以更快的方式搜索大数组?

标签 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 没有绑定(bind)。此外,它似乎返回找到的值而不是索引。以及如何将找到的内容保存到 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]));

但最后的代码没有编译

最佳答案

由于这个过程将重复多次,我建议您对元素进行排序并将其与索引成对存储在 vector 中。给定此 vector ,您可以轻松找到基本索引。

      vector<pair<int, int> > sortedElementsWithIndex;

Pair 包含原始数组中的元素和索引。您可以根据元素值对该 vector 进行排序。

关于c++ - STL 是否有助于在 C++ 中以更快的方式搜索大数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17849428/

相关文章:

c++ - 使用 C/C++ 在 OSX 中获取进程创建日期时间

c++ - 跟踪动态内存

c++ - 我无法在解决方案资源管理器 Visual Studio Community 2015 中运行多个文件

c++模板不带参数使用

javascript - asp中继器模板条件验证javascript

php - PHP 是否有一种与 Django 模板语言几乎相似的模板语言?

php - 搜索结果错误

c++ - unique_ptr、make_unique 和多态性

PHP mysql_query 返回解码后的编码数据

search - 修改Windows 7的“开始”菜单搜索算法?