stl有助于在c++中以更快的方式搜索大数组吗
does stl help to to search a big array in faster way in c++?
我有一个大矩阵,它可以大到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;
对包含原始数组中的元素和索引。您可以根据元素值对这个向量进行排序。
相关文章:
- 如何在c++中为模板函数实例创建快捷方式
- 有根的二进制搜索树.保留与其父级的链接
- 在c代码之间共享数据的最佳方式
- 在C++中将函数压缩为两种方式
- 在C++中搜索嵌套多映射值
- 以螺旋方式打印矩阵的程序.(工作不好)
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- C++以迭代方式搜索混合类型地图
- 查找函数在unordered_map中的工作方式是搜索键值
- 在哪种方式搜索容器中的元素的方式更有效
- C++以广度优先搜索的方式查找多个数组中元素的所有组合
- 在C++中存储和搜索数字的最佳方式
- stl有助于在c++中以更快的方式搜索大数组吗
- 以最快的方式搜索boost multi_index容器
- 搜索std::集的最佳方式
- 如何以最佳、最简单的方式在文件中搜索
- 当条目以有序的方式添加时,二叉搜索树有效地充当链表
- 使用c++在非常大的文本文件(10gb)中搜索多个单词是最快的方式
- 最快的方式做关键字搜索在大文本在C/ c++
- 以编程方式自定义 DLL 搜索目录