c++ - 列表中的性能过滤
问题描述
我有这段代码会执行得非常糟糕,越多的项目进入m_songs
我正在寻找一些优化。内部 forloop 是这里的罪魁祸首,因为m_songs
随着时间的推移,forloop 循环遍历所有项目以检查缓存中是否有某些项目。我将如何更有效地重写它?
for(auto& const filename : filenames) {
auto alreadyInCache = false;
for(unsigned int i = 0; i < m_songs.size(); i++) {
if(filename == m_songs[i]->filename) {
alreadyInCache = true;
}
}
if(alreadyInCache) {
continue;
} else {
// add items to m_songs;
}
}
// Overwrite our cache with the latest m_songs
好的,我已经更新了我的代码以使用find_if()
在文件名的 forloop 中,我现在正在这样做:
auto it = std::find_if(m_songs.begin(), m_songs.end(), [filename](std::shared_ptr<Song> n) {
return n->filename == filename;
});
auto alreadyInCache = it != m_songs.end();
if(alreadyInCache) continue;
这会更有效率吗?还能进一步改进吗?
解决方案
如果m_songs
是一个 sorted vector
,我假设它看起来就像填充它的相同代码( ),那么您可以使用而不是逐个元素检查// add items to m_songs
来执行二进制搜索。std::lower_bound
如果您还没有按顺序添加元素,请按以下步骤操作:如何将值插入已排序的向量中?
推荐阅读
- wpf - 无法在wpf中将点击事件添加到按钮
- activemq-artemis - AIO 不在此平台上,它将回退到使用纯 Java NIO
- laravel - 如何修复错误'stream_copy_to_stream(): read of 8192 bytes failed with errno=21 Is a directory' in Larvel?
- python - 如何在数据框中为 groupby 做 Python
- python - python覆盖没有代码源(内置)
- json - 什么是标记语言?(XML vs YAML vs JSON)
- angular - 从Angular Post请求获取参数到Spring作为对象,而不是字符串
- python - 转置 Excel 表格的第一列,删除空单元格并将其附加到特定行
- javascript - 每当我尝试使用 .map 获取数据时,都会出错
- javascript - 如何使用javascript在树枝中循环更改div的背景颜色