【问题标题】:Performance filtering within a list列表中的性能过滤
【发布时间】:2018-06-04 20:51:12
【问题描述】:

我有这段代码,如果进入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;

这会更有效吗?是否可以进一步改进?

【问题讨论】:

  • 您考虑过使用set/map/unordered_set/unordered_map吗?
  • @NathanOliver 我没有,因为我对 c++ 很不熟悉,谢谢,我会调查一下!
  • @NathanOliver 在水下它是一个包含自定义类的共享指针的向量。我已经通过find_if() 的尝试更新了我的问题,还有什么可以改进的吗?
  • 如果你可以使用唯一的指针。但我担心你需要一个高级的字符串比较功能。

标签: c++ performance list optimization


【解决方案1】:

如果m_songs 是排序后的vector,我认为它看起来是相同的代码正在填充它(// add items to m_songs),那么您可以使用std::lower_bound 执行binary search 而不是检查逐个元素。

如果您还没有按顺序添加元素,请按以下步骤操作:how do you insert the value in a sorted vector?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 2020-02-08
    • 2015-11-28
    • 2011-05-01
    • 2022-11-24
    • 2017-10-07
    相关资源
    最近更新 更多