Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/148.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 常量id、运算符=和向量擦除-它们可以一起工作吗?_C++_C++11_Vector_Constants_Erase - Fatal编程技术网

C++ 常量id、运算符=和向量擦除-它们可以一起工作吗?

C++ 常量id、运算符=和向量擦除-它们可以一起工作吗?,c++,c++11,vector,constants,erase,C++,C++11,Vector,Constants,Erase,我有一群人。当时我认为给每个人一个独一无二的身份证是个好主意,所以我做到了: class Person { Person::Person(): id(currentID++){ } const int id; } 过了一段时间,我想建立一个人物向量,因此我知道我必须提供: 向量的元素必须是: Copyable, i.e. have a constructor compatible with T(const T&) Assignable, i.e. have an

我有一群人。当时我认为给每个人一个独一无二的身份证是个好主意,所以我做到了:

class Person {
    Person::Person(): id(currentID++){
    }
    const int id;
}
过了一段时间,我想建立一个人物向量,因此我知道我必须提供:

向量的元素必须是:

Copyable, i.e. have a constructor compatible with T(const T&)
Assignable, i.e. have an operator= compatible with operator=(const T&).
Default-constructible, i.e. have a constructor compatible with T().
所以我尽了最大努力,想出了

Person::Person(const Person& other): id(other.id) {
}
Person& Person::operator=(const Person& other) 
}
一切似乎都很顺利

但是有一天我试图从向量中删除一个元素

矢量人;
人。推回(人())//id 0
人。推回(人())//id 1
人。推回(人())//id 2
向量::迭代器;
for(it=persons.begin();it!=persons.end();){
如果(it->getID()==1){
它=人。擦除(它);
}否则{
it++;
}
}
//persons.size()==1
我检查了调试器,发现erase使用
操作符=
在调用erase之后移动元素。显然id并没有改变,所以我删除了向量中id 1之后的每个元素

为什么会这样?我一直认为向量擦除只会将指针从元素0移动到2,从而删除元素1

我应该如何处理我的
常量id
?我应该把它包括在
操作符=
中吗


我在C+11中读到一个移动操作符(我使用),如果我提供它,vector会使用这个特殊操作符吗?

如果你能发布有效的代码,那就太好了。赋值运算符的语义毫无意义,赋值后这两个对象仍然不同。看起来您有用于
id
的访问器函数,那么让它成为
const
有什么意义呢?去掉
常量
,如果你的类真的这么简单,就去掉复制构造函数和赋值操作符。让编译器为您生成这些。你的问题应该解决。另外,搜索erase remove习语,寻找从
向量
中删除项的另一种方法。@Danvil的可能重复项有点不愿意将其作为该项的重复项关闭,因为OP通过编写(断开的)复制赋值操作符绕过了可赋值要求。但他基本上面临着与另一个问题相同的问题。只是不要使用
const
数据成员。不要提供对它的任何公共或受保护的访问。
vector<Person> persons;
persons.push_back(Person()); //id 0
persons.push_back(Person()); //id 1
persons.push_back(Person()); //id 2

vector<Person>::iterator it;
for(it = persons.begin() ; it != persons.end() ; ) {
    if(it->getID() == 1) {
        it = persons.erase(it);
    } else {
        it++;
    }
}
//persons.size() == 1