我想从矢量中删除对象。矢量通过引用传递,我迷路了。我已经尝试过brickList.erase(它)以及组合擦除删除,但我无法弄清楚正确的表达式。
有人会这么善意帮我评论一下吗?在一般情况下,让我们说100块砖随机位置。
#include "stdafx.h"
#include <iostream>
#include <vector>
class Brick {
private:
int position;
public:
Brick(int);
int getPosition();
};
Brick::Brick(int p) : position(p) {};
int Brick::getPosition() { return position; }
void removeBricks(int a, int b, std::vector<Brick> &brickList) {
std::vector<Brick>::iterator it;
for (it = brickList.begin(); it != brickList.end(); ++it) {
int currentPos = (*it).getPosition();
if (currentPos >= a && currentPos <= b) {
// here I need help to delete objects
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<Brick> myBricks;
for (int i = 0; i<10; ++i) {
Brick tmp_brick(i);
myBricks.push_back(tmp_brick);
}
// delete all bricks with position between 3 and 5
removeBricks(3, 5, myBricks);
system("pause");
return 0;
}
答案 0 :(得分:2)
从您的代码中
// delete all bricks with position between 3 and 5
//removeBricks(3, 5, myBricks); // <-- replace this
myBricks.erase(myBricks.begin()+3,myBricks.begin()+5); // <-- with this
使用基于范围的erase
函数。您根本不需要removeBricks
功能。
如果 使用removeBricks()
功能,您可以使用相同的函数原型进行此操作。
void removeBricks(int a, int b, std::vector<Brick> &brickList) {
// check a >= 0, a < b and b doesn't exceed length of brickList
brickList.erase(brickList.begin()+a,brickList.begin()+b);
}
编辑:似乎您的位置概念不是指您的项目的数组位置,而是Brick
的成员函数的值。这应该适合你。
void removeBricks(int a, int b, std::vector<Brick> &brickList)
{
std::vector<Brick>::iterator it;
for (it = brickList.begin(); it != brickList.end(); /* DONT increment here*/) {
int currentPos = (*it).getPosition();
if (currentPos >= a && currentPos <= b) {
// store the return value from erase!!
it = erase(it);
}
else
{
// increment here rather than in the for loop incrementer
it++;
}
}
}
您必须存储erase
的返回值,因为迭代器会失效。上面的内容应该对你有用,虽然vector不是容器的最佳选择,因为由于底层数组的重组,擦除项可能很慢。