假设我有
#include <string>
#include <vector>
using namespace std;
struct Student
{
const string name;
int grade;
Student(const string &name) : name(name) { }
};
那么,我该如何保持学生的 vector ?
int main()
{
vector<Student> v;
// error C2582: 'operator =' function is unavailable in 'Student'
v.push_back(Student("john"));
}
有没有办法做到这一点,还是我必须在堆上分配所有学生,然后存储一个指向每个学生的指针?
最佳答案
你不能。您的类型违反了标准容器的“可分配”要求。
ISO/IEC 14882:2003 23.1 [lib.container.requirements]/3:
The type of objects stored in these components must meet the requirements of
CopyConstructible
types (20.1.3), and the additional requirements ofAssignable
types.
来自表 64(可分配
要求):
In Table 64,
T
is the type used to instantiate the container,t
is a value ofT
, andu
is a value of (possiblyconst
)T
.expression:
t = u
; return type:T
; post-condition:t
is equivalent tou
理论上,std::vector
等价物可以选择在所有情况下进行销毁和复制构造,但这不是已选择的契约。如果不需要重新分配,则对 vector::operator=
和 vector::assign
之类的内容使用包含类型的赋值运算符可能会更有效。
关于c++ - 具有 const 成员的结构 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8467968/