我正在开发一个拥有包含大量汽车的容器的车队计划
std::map<CarKey, Car> _cars;
我需要编写一个函数/类来操作_cars中汽车对象的子集
天真地我可以使用过滤功能迭代_cars
for(auto& p : _cars){
//please note: I cannot get things done with one iteration, I have to iterate many times to get things done
if (isOfInterest(p.second)){
// do some thing
}
}
这种解决方案的缺点是,我只对10%的汽车感兴趣,我将不得不浪费很多时间迭代
我试图找到一种优雅的方式来返回我感兴趣的所有迭代器
std::vector<std::map<CarKey, Car> :: iterator > getAllIntereted(_cars)
那么我可以简单地遍历矢量
我不确定这是不是一个好方法。也许有一些设计模式可能会有所帮助?
任何人都可以提供任何见解吗?
谢谢
在没有看到更多代码的情况下,我认为返回包含指向您感兴趣的汽车的指针的向量是一个很好的解决方案。指针,因为否则您正在创建重复的对象。
但是,如果您可以在识别汽车的同一循环中完成工作,我认为这将是最好的。只是取决于这是否实用。