当我尝试从向量中删除对象时出现错误
谷歌搜索,但我不明白怎么了。从我收集到的信息中,我正确地调用了擦除功能,但是我必须为类提供一个移动赋值运算符?
我称之为擦除的函数
void removegroup(const short &group){
switch (tracker[group].group){
case 0: {
guardvec.erase(guardvec.begin()+tracker[group].position); //this is the problem it compiles just fine if i comment out this line
//guardvec.erase(remove(guardvec.begin(), guardvec.end(), tracker[group].position),guardvec.end()); //tried this and it doesnt work
}
break;
}
for (short counter=0;counter<tracker.size();counter++)
if ((tracker[counter].group==tracker[group].group)&&(tracker[counter].position>tracker[group].position))
tracker[counter].position=tracker[counter].position--;
}
我的班级
class guardhitdice {
friend class guard;
short const times = 2, dice = 8, plus = 2;
};
class guard : private guardhitdice {
private:
short units, XP, morale, totalHP=0, dead=0, wounded=0;
short* HP = new short[units];
public:
void showstats(){
std::cout << "STR=1, DEX=1, CON=1, INT=0, WIS=0, CHA=0, Perception=2, Passive Perception=12"<<std::endl
<<"current xp: "<<XP<<"total HP across units: "<<totalHP<<"casualties: "<<dead<<"wounded: "<<wounded;
}
void initializeHP(){
for (short counter=0; counter<units-1; counter++){
HP[counter]=plus + D(times, dice);
totalHP+=HP[counter];
}
}
guard(const short &xp, short &Units, short &Morale){
XP=xp;
units=Units;
morale=Morale;
// short* HP = new short[units];
initializeHP();
}
~guard(){
delete HP;
}
};
这是我的编译器错误https://pastebin.com/KSniFkVD 它应该能够删除tracker [group] .position处的对象。顺便说一句位置是空头 我还尝试将其添加到我的课程中,但是它们不起作用
guardhitdice& guardhitdice ::operator=(guardhitdice&&);
guard& guard ::operator=(guard&&);
如果我对法向矢量执行此操作,但对对象矢量不适用
答案 0 :(得分:2)
您的问题可以减少到
#include <vector>
class test{
short const times = 2;
};
int main()
{
std::vector<test> t;
t.push_back(test{});
t.erase(t.begin()); //<-- BAM!
}
vector
进行了大量复制和分配。复制很酷,但是测试包含一个const
成员。您无法更改const
变量,因此无法进行分配。
但是,由于它是使用文字进行初始化的,并且没有允许将该值初始化为其他值的构造函数,因此test
的所有实例都将具有相同的值。这非常适合static
。 static
变量不参与赋值,因此可以使用默认赋值运算符。
class test{
static short const times = 2;
};