c++ - 如何改进这些嵌套的 for 循环

标签 c++ performance loops sorting

我有以下代码:

// vector of elements
vector<Graphic> graphics;

// vector of indexes of the selected graphic elements
vector<int> selected_indexes;

// vector according to which the graphic elements have to be "sorted" and parsed
vector<short> order;

for (auto o : order)
{
    for (auto i : selected_indexes)
    {
        const auto& g = graphics[i];

        if (g.position() == o)
        {
            // parse g
        }
    }
}

我有一个自定义元素的 vector 以及已选择要解析的元素的索引,但是必须解析这些元素的顺序取决于它们的 position()根据第三个 vector 的值。

有没有办法改进这些嵌套循环,避免对将被跳过的元素反复迭代,因为它们的位置不等于当前顺序?

最佳答案

假设只有一个 Graphic具有给定 position() 的对象:

构建 unordered_map : intGraphics* ,你称之为例如gp ,所以 gp[i]->position() = i .

构建 map 是线性时间,对每个索引使用它大致是恒定时间。

for( auto o : order )
{
    auto const& g = *gp[o];
    // parse g
}

如果可以有多个 Graphics给定位置的对象,构建 unordered_map : intvector<Graphic*> ,然后使用类似的使用代码

for( auto o : order )
{
    for( auto const p : gp[o] )
    {
        auto const& g = *p;
        // parse g
    }
}

或者,对于最后一种情况,您可以使用 unordered_multimap .

关于c++ - 如何改进这些嵌套的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39220854/

相关文章:

c++ - 为什么 std::bind 在这个例子(成员函数)中没有占位符就不能工作?

sql-server - SQL Server性能: GROUP BY int vs GROUP BY VARCHAR

java - 电脑socket的速度是120MB/s,正常吗?

JavaScript 如果答案正确,则生成新字符串

c - 我想知道当 if(i%2) 它检查什么来继续时会发生什么。它错过了 == 但它打印出的总和为 20?为什么?

c++ - 代码块编译不可执行

c++ - (int **array;) 创建了什么?

c++ - wxTextCtrl 类的 GetValue 方法使我的应用程序崩溃

java - 分析程序时出现大量 char[] 实例

gwt - 在 GWT 中,如何在面板内循环 Gui Widget?