如何改进这些嵌套的for循环
How to improve these nested for loops
我有以下代码:
// 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
: int
→vector<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
矢量中,我不确定是否会有任何奇怪的副作用。
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么我的for循环不能正确获取argv
- 在基于范围的for循环中使用结构化绑定声明
- 通过for循环使用用户输入填充列表
- 使用for循环检查数组中的重复项
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 正在使用for循环创建QScatterSerie
- Python中的for循环与C++有何不同
- 在更改for循环的第三部分后,未使用for循环结果
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)
- 如何用for循环在c++中生成单词三角形
- 如何在for循环中包含两个索引值的测试条件
- 带有多个独立参数的C++For循环
- 为什么我的程序在for循环中k=0时返回垃圾值
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- C++-For循环未执行
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- C++ 无法在字符数组中使用 for 循环打印字母模式