1

我有一个大矩阵,可能大到 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]));

但最后的代码没有编译

4

1 回答 1

4

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

      vector<pair<int, int> > sortedElementsWithIndex;

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

于 2013-07-25T05:16:16.707 回答