使用std::list改进简单性
Improving simplicity with std::list
有什么更好(更干净、更可读和/或更高效(的方法可以做到这一点:
std::list<Fruit*> Apples;
std::list<Fruit> Basket;
for (std::list<Fruit*>::iterator niApple(Apples.begin());
niApple != Apples.end(); niApple++) {
for (std::list<Fruit>::iterator niBasket(Basket.begin());
niBasket != Basket.end(); niBasket++) {
if (&(*niBasket) == *niApple) {
Basket.erase(niBasket);
break;
}
} // loop
} // loop
你推荐什么?我主要需要将要放在篮子里的苹果的句柄,这样就可以从篮子里删除苹果,而不必搜索(例如,通过固定数组内的索引(。但是,Basket需要在进程中分配和解除分配内存。
另一种C++11方式:
list<Fruit*> Apples;
list<Fruit> Basket;
Basket.remove_if([](const Fruit& fruit) {
return any_of(Apples.begin(), Apples.end(), [](Fruit* apple) {
return &fruit == apple;
});
});
现在将第一个容纳迭代器的容器更改为第二个:
list<list<Fruit>::iterator> Apples;
list<Fruit> Basket;
for (auto apple : Apples)
Basket.erase(apple);
通过这种方式,您可以获得更好的性能,并且对接口几乎没有更改,因为迭代器在大多数情况下的行为就像指针。
还可以看看以下内容:是否应该弃用std::list?
请注意,要使两个解决方案都工作,Basket
容器必须是std::list
。
std::list<Fruit*> Apples;
std::list<Fruit> Basket;
auto is_apple = [](const Fruit& frt) {
for(auto apl: Apples) { //for each Apple pointer
if (apl== &frt) //if it points at the current fruit
return true; //then it's one of the apples
}
return false; //otherwise it's not one of the apples
};
Basket.remove_if(is_apple);
这对我来说似乎更简单。(Hooray C++11!(
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 在c++中用vector填充一个简单的动态数组
- (C++)分析树以计算返回错误值的简单算术表达式
- 如何在 C 中正确使用 libiconv 使其不会报告"Arg list too long"?
- C++中带有List类的迭代器Segfault
- 使用"std::unordereded_map"映射到"std::list"对象
- 我的简单if-else语句是如何无法访问的代码
- 使用简单类型列表实现的指数编译时间.为什么
- GCC对可能有效的代码抛出init list生存期警告
- 如何在BST的这个简单递归实现中消除警告
- 使用std::list创建循环链表
- 一种在C++中读取TXT配置文件的简单方法
- 重载Singly Linked List中的赋值运算符
- 关于简单C++函数(is_palindrome)的逻辑的问题
- 显示错误输出的简单数组排序程序
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 退出简单while循环时出现问题
- std::list 可以用于简单的无锁队列吗?
- c++中简单迭代list over map的性能比较