如何从 std::list 中删除元素?
Howto drop a element from std::list?
有一个列表ob对象并进入std::for_each调用每个对象,但需要在完成任务时删除每个对象以清除内存并在经过的时间内调用多个对象,需要删除并添加项目:
类定义:
#include "CoreLog.h"
#include "physical_objects/Rectangle.h"
#include "GL/freeglut.h"
#include "GL/gl.h"
#include <iostream>
#include <list>
#include <vector>
#include <algorithm>
// #include <random>
using namespace std;
class Core
{
private:
CoreLog coreLog;
std::list<Rectangle> rectangles;
public:
void init();
void draw();
};
初始函数为:
void Core::init()
{
for(float i; i <= 2.0; i += 0.1)
{
Rectangle rectangle;
rectangle.setLeft(-1.0 + i);
rectangle.setTopToBottomInSeconds(1.0 + i);
this->rectangles.push_back(rectangle);
}
}
在循环中需要删除每个项目:
void Core::draw()
{
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable( GL_BLEND );
glClearColor(0.4, 0.4, 0.4, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
for (Rectangle &rectangle : this->rectangles)
{
// Draw object
rectangle.draw();
if(!rectangle.getIsVisible())
{
this->rectangles.erase(std::find(this->rectangles.begin(), this->rectangles.end(), rectangle));
}
}
// TODO: Add new rectangles here if is necessary.
}
但是编译器显示错误:
core/Core.cc:44:101:从这里需要/usr/include/c++/5/bits/predefined_ops.h:194:17:错误:不匹配 'operator=='(操作数类型为"矩形"和"常量矩形")
我尝试更改为常量矩形:
const Rectangle r;
r = rectangle;
this->rectangles.erase(std::find(this->rectangles.begin(), this->rectangles.end(), r));
但同样的问题。并尝试添加运算符:
bool operator == (const Rectangle &a, const Rectangle &b);
this->rectangles.erase(std::find(this->rectangles.begin(), this->rectangles.end(), rectangle));
但同样的问题:
core/Core.cc:44:93:从这里需要/usr/include/c++/5/bits/predefined_ops.h:194:17:错误:不匹配 'operator==' (操作数类型为"矩形"和"常量矩形") { 返回 *__it == _M_value;}
对于编译,我使用:
CCFLAGS += -lglut -lGL -Wall -Wextra -std=gnu++11
main:
g++
core/CoreLog.cc
core/physical_objects/Rectangle.cc
core/Core.cc
main.cc
$(CCFLAGS)
-o compiled/main
chmod +x compiled/main
您需要定义 Rectangle == 运算符。
函数为:
//Put this function outside the Rectangle class and implement it
bool operator ==(const Rectangle &a, const Rectangle &b)
{
//here you need to implement the == operator
}
此外,您的代码将崩溃,因为您擦除了for_each循环中的元素。这将使迭代器失效。你需要更加小心。
您可以使用擦除
std::list<Rectangle*>::iterator rect = rectangles.begin();
while (rect != rectangles.end())
{
if (!rect->getIsVisible())
{
rect = rectangles.erase(rect);
}
else
{
++rect;
}
}
您也可以使用 STL 并在一行中解决它
rectangles.remove_if([](Rectangle const& rect){!(rect.getIsVisible());});
相关文章:
- 如何从存储在std::映射中的std::集中删除元素
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 从矢量中删除元素后出现隔离错误
- 如何使用remove_if从矢量中删除元素
- 如何从使用 for 循环中的矢量大小的矢量中删除元素
- C++映射不删除元素
- 如何从标准::元组中删除元素?
- 在动态数组中添加/删除C++元素
- 如何通过比较彼此的成员从QStringList中删除元素
- 如何修复从矢量中删除元素的错误?
- 从 std::set 中删除元素,同时在 C++17 中迭代该元素
- 使用remove_if从矢量中删除元素
- 用C++从三维矢量中删除元素
- 从对象数组中删除元素
- 如何在不使用 vector::erase() 的情况下编写自定义 Vector 方法来删除元素?
- C++ - 按自定义数据类型向量的值删除元素
- 从任意容器中廉价删除元素的惯用方法?
- 从数组中删除元素不起作用的函数
- 删除元素 BST
- 从向量中删除元素时未处理的异常