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

How to improve these nested for loops

本文关键字:for 循环 嵌套 何改进      更新时间:2023-10-16

我有以下代码:

// 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
        }
    }
}

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

是否有一种方法可以改进这些嵌套循环,避免在那些因为位置不等于当前顺序而被跳过的元素上反复迭代?

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

构建unordered_map: int & rrr;Graphics*,你称之为例如gp,这样gp[i]->position() = i

建立地图是线性时间,使用它为每个索引是常数时间,大致。

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

你已经知道你想要处理多少元素,所以你可以使用一个向量来保持指针指向你的Graphic实例,已经分配了适当数量的元素:

vector<Graphic*> selected(selected_indexes.size(), nullptr);

然后你可以用元素填充这个向量,使用order:

排序
for (auto index: selected_indexes) {
  auto where = std::find_if(order.begin(), order.end(), [&graphics, index] (short i) { return i == graphics[index].position(); });
  selected[*where] = &graphics[index];
}

你可以创建一个临时的向量来代替嵌套。

vector<Graphic> selectedGraphics; //maybe use ptr here
selectedGraphics.reserve(selected_indexes.size());
for(auto i : selected_indexes)
    selectedGraphics.push_back(graphics[i]);
//then sort according to your order
std::sort(selectedGraphics.begin(),selectedGraphics.end(),[order](auto left, auto right)
{
    //the iterator of the position of "left" is further in front of the position of "right"
    return order.find(left.position()) < order.find(right.position());
});
//then process
for(auto graphic : selectedGraphics)
    //do whatever

排序假定order向量项与selectedGraphics向量项匹配。如果选定的图形对象的位置不在order矢量中,我不确定是否会有任何奇怪的副作用。